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

Python 在图形X轴上显示月份而不是天数,python,matplotlib,Python,Matplotlib,我有两个图形共享相同的X轴,并绘制在一个图形上(即一个X轴和两个y轴)。问题是,显示在共享X轴上的时间框架过于详细,显示的是天而不是月(我更喜欢) 希望X轴显示月份而不是日期您可以使用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轴,并绘制在一个图形上(即一个X轴和两个y轴)。问题是,显示在共享X轴上的时间框架过于详细,显示的是天而不是月(我更喜欢)


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

您可以使用
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轴的类型或范围,但我希望解决方案是。

您可以简单地使用
日期格式化程序
功能,并将其应用于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()
这将导致以下结果:


此外,您可能需要使用
月定位器()
来确保实际的节拍都在月初。(否则2019-04-29等日期仍将标记为4月)
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()