在图形X轴上显示月而不是天

时间:2019-05-06 08:35:10

标签: python matplotlib

enter image description here

我有2个图形,它们共享相同的X轴,并绘制在一个图形上(即一个X和两个y轴)。问题是共享X轴上显示的时间框架过于详细,显示的是日期而不是月份(我希望是几个月)。

[fig1, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('Months')
ax1.set_ylabel('Price', color=color)
ax1.plot(df\['2019'\]\['Price'\], color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('RSI', color=color)  # we already handled the x-label with ax1
ax2.plot(RSI(df\['2019'\]\['Price'\]), color=color)
ax2.tick_params(axis='y', labelcolor=color)

fig.tight_layout()  
plt.show()][1]

期望X轴显示月份而不是日期

2 个答案:

答案 0 :(得分:1)

您可以简单地使用DateFormatter函数并将其应用于x轴数据。 我使用一些示例数据创建了一个解决方案,并用“销售”信息代替了RSI。

import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.dates as mdates

#Sample Data
data = [['2019-03-20',10, 1000],['2019-04-04',22,543],['2019-11-17',13,677]]
df = pd.DataFrame(data,columns=['Date','Price','Sales'])

# DateFormatter object to use abbreviated version of month names
monthsFmt = mdates.DateFormatter('%b')

fig1, ax1 = plt.subplots()

color = 'tab:red'
ax1.set_xlabel('Months')
ax1.set_ylabel('Price', color=color)
ax1.plot(pd.to_datetime(df['Date'], infer_datetime_format=True), df['Price'], color=color)
ax1.tick_params(axis='y', labelcolor=color)

ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis

color = 'tab:blue'
ax2.set_ylabel('Sales', color=color)  # we already handled the x-label with ax1
ax2.plot(pd.to_datetime(df['Date'], infer_datetime_format=True), df['Sales'], color=color)
ax2.tick_params(axis='y', labelcolor=color)

# Apply X-axis formatting at the end
ax2.xaxis.set_major_formatter(monthsFmt)

fig1.tight_layout()
plt.show()

这将导致以下结果:

Result Image

答案 1 :(得分:0)

您可以使用xticks方法来设置图形中刻度线的位置和标签。例如:

plt.xticks( [1,2,3,4,5,6,7,8,9,10,11,12], ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']

请注意,第一个列表是轴上刻度线的位置,第二个是标签。从所附的图片中,无法了解您的x轴的类型或范围,但我希望解决方案是