Я пытаюсь установить x тики моего подграфика осей, но это не работает для меня. Сейчас у меня есть следующий фрейм данных:
Я использую следующий код, чтобы построить это:
ax=predictions.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4),
legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
ax
И результат следующий:
Как вы можете видеть, месяц август написан как август 2021 года. Я хотел бы иметь возможность изменить все отметки x либо только на месяц, либо на месяц с годом (например, сохранить июль или установить июль 2021 года).
Я пытался использовать ax.set_xticks
, но пока это не сработало для меня.
Заранее спасибо!
Решение проблемы
Не сохраняйте predictions.plot()
вывод в ax
. Вы просто получите список строк. После реализации приведенного ниже решения вы можете просмотреть вывод с помощью plt.show()
.
При работе с датами, которые являются datetime
объектами
Для ярлыков с «июль 2021 г.», «август 2021 г.» и т. д. используйте
import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object
# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index
# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{date.strftime("%b")} {date.strftime("%Y")}' for date in dates_index]
print(labels)
plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4),
legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot
Для ярлыков с «21 июля», «21 августа» и т. д. используйте
import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object
# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index
# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{date.strftime("%b")} {date.strftime("%y")}' for date in dates_index]
print(labels)
plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4),
legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot
Для ярлыков с «июль», «август» и т. д. используйте
import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object
# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index
# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{date.strftime("%b")}' for date in dates_index]
print(labels)
plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4),
legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot
При работе с датами, которые являются str
объектами
Для ярлыков с «июль 2021 г.», «август 2021 г.» и т. д. используйте
import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object
# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index
# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{(datetime.datetime.strptime(date, "%Y-%m-%d")).strftime("%b")} {datetime.datetime.strptime(date, "%Y-%m-%d").year}' for date in dates_index]
print(labels)
plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4),
legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot
Для ярлыков с «21 июля», «21 августа» и т. д. используйте
import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object
# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index
# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{(datetime.datetime.strptime(date, "%Y-%m-%d")).strftime("%b")} {datetime.datetime.strptime(date, "%Y-%m-%d").strftime("%y")}' for date in dates_index]
print(labels)
plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4),
legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot
Для ярлыков с «июль», «август» и т. д. используйте
import datetime
import matplotlib.pyplot as plt # Matplotlib.pyplot object
# Please note that df is a DataFrame object. Substitute your DataFrame object's name below.
dates_index = df.index
# You can use df.index in the list comprehension as well as in the plt.plot and plt.xticks operations as an alternative to dates_index.
labels = [f'{(datetime.datetime.strptime(date, "%Y-%m-%d")).strftime("%b")}' for date in dates_index]
print(labels)
plt.plot(y=['Actual','add_add','add_mul','mul_add','mul_mul','Philips'],figsize=(5,4),
legend=True,color=['b','r','g','m','y','black'],ylabel='Quantity',xlabel='Date')
plt.xticks(dates_index, labels)
plt.show() # Visualize the plot
Комментариев нет:
Отправить комментарий