将 Xticks 频率设置为数据帧索引 [英] Set Xticks frequency to dataframe index
问题描述
我目前有一个数据框,它以 1990 年到 2014 年(25 行)的年份作为索引.我希望我的情节显示所有年份的 X 轴.我正在使用 add_subplot,因为我计划在这个图中有 4 个图(它们都具有相同的 X 轴).
I currently have a dataframe that has as an index the years from 1990 to 2014 (25 rows). I want my plot to have the X axis with all the years showing. I'm using add_subplot as I plan to have 4 plots in this figure (all of them with the same X axis).
要创建数据框:
import pandas as pd
import numpy as np
index = np.arange(1990,2015,1)
columns = ['Total Population','Urban Population']
pop_plot = pd.DataFrame(index=index, columns=columns)
pop_plot = df_.fillna(0)
pop_plot['Total Population'] = np.arange(150,175,1)
pop_plot['Urban Population'] = np.arange(50,125,3)
我目前拥有的代码:
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(2,2,1, xticklabels=pop_plot.index)
plt.subplot(2, 2, 1)
plt.plot(pop_plot)
legend = plt.legend(pop_plot, bbox_to_anchor=(0.1, 1, 0.8, .45), loc=3, ncol=1, mode='expand')
legend.get_frame().set_alpha(0)
ax1.set_xticks(range(len(pop_plot.index)))
这是我得到的情节:
当我评论 set_xticks 时,我得到以下图:
When I comment the set_xticks I get the following plot:
#ax1.set_xticks(range(len(pop_plot.index)))
我尝试了在这里找到的几个答案,但都没有取得多大成功.
I've tried a couple of answers that I found here, but I didn't have much success.
提前致谢.
推荐答案
不清楚 ax1.set_xticks(range(len(pop_plot.index)))
应该用于什么.它会将刻度设置为数字 0、1、2、3 等,而您的绘图范围应从 1990 年到 2014 年.
It's not clear what ax1.set_xticks(range(len(pop_plot.index)))
should be used for. It will set the ticks to the numbers 0,1,2,3 etc. while your plot should range from 1990 to 2014.
相反,您希望将刻度设置为数据的数量:
Instead, you want to set the ticks to the numbers of your data:
ax1.set_xticks(pop_plot.index)
完整更正示例:
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
index = np.arange(1990,2015,1)
columns = ['Total Population','Urban Population']
pop_plot = pd.DataFrame(index=index, columns=columns)
pop_plot['Total Population'] = np.arange(150,175,1)
pop_plot['Urban Population'] = np.arange(50,125,3)
fig = plt.figure(figsize=(10,5))
ax1 = fig.add_subplot(2,2,1)
ax1.plot(pop_plot)
legend = ax1.legend(pop_plot, bbox_to_anchor=(0.1, 1, 0.8, .45), loc=3, ncol=1, mode='expand')
legend.get_frame().set_alpha(0)
ax1.set_xticks(pop_plot.index)
plt.show()
这篇关于将 Xticks 频率设置为数据帧索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!