表d中的Pythng绘图轴

2024-03-29 08:09:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习python,一直在尝试从表中绘制数据。 下面是我的一段代码:

    df1 = populationReport.loc[['Time','VIC','NSW','QLD']]

    df1 = df1.set_index('Time')

    print(df1)

    plt.plot(df1)
    plt.legend(df1.columns)
    plt.ylabel ('Population')
    plt.xlabel ('Timeline')


    plt.show()

我需要X轴来显示“时间”列中的信息。 但到目前为止,它只在我的表中显示行号

附加图像显示所需的绘图,但x轴不应显示条目数,而应显示“时间”列中的数据 my draft plot

以下是表格的外观:

           VIC        NSW        QLD
Time                                    
1/12/05  5023203.0  6718023.0  3964175.0
1/3/06   5048207.0  6735528.0  3987653.0
1/6/06   5061266.0  6742690.0  4007992.0
1/9/06   5083593.0  6766133.0  4031580.0
1/12/06  5103965.0  6786160.0  4055845.0

Tags: 数据代码indextimeplot时间绘制plt
1条回答
网友
1楼 · 发布于 2024-03-29 08:09:54

我认为您可以使用^{},如果需要,可以定义formatdayfirst参数:

df1 = populationReport[['Time','VIC','NSW','QLD']]
df1['Time'] = pd.to_datetime(df1['Time'], format='%d/%m/%y')
#alternative
#df1['Time'] = pd.to_datetime(df1['Time'], dayfirst=True)
df1 = df1.set_index('Time')
print (df1)
                  VIC        NSW        QLD
Time                                       
2005-12-01  5023203.0  6718023.0  3964175.0
2006-03-01  5048207.0  6735528.0  3987653.0
2006-06-01  5061266.0  6742690.0  4007992.0
2006-09-01  5083593.0  6766133.0  4031580.0
2006-12-01  5103965.0  6786160.0  4055845.0

然后可以使用^{}

import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

ax = df1.plot()
ticklabels = df1.index.strftime('%Y-%m-%d')
ax.xaxis.set_major_formatter(ticker.FixedFormatter(ticklabels))
plt.show()

相关问题 更多 >