从Pandas DataFrame绘制和格式化Seaborn图表
我有一个名为 al_df
的 pandas 数据框,里面包含了最近美国人口普查中阿拉巴马州的人口数据。我创建了一个累积函数,并用 seaborn
画出了这个图表:
与绘图相关的代码如下:
figure(num=None, figsize=(20, 10))
plt.title('Cumulative Distribution Function for ALABAMA population')
plt.xlabel('City')
plt.ylabel('Percentage')
#sns.set_style("whitegrid", {"ytick.major.size": "0.1",})
plt.plot(al_df.pop_cum_perc)
我有几个问题: 1) 我该如何更改刻度,让 y 轴每 0.1 个单位显示一条网格线,而不是默认的每 0.2 个单位? 2) 我该如何更改 x 轴,让它显示城市的实际名称,并且竖着排列,而不是显示城市的“排名”(来自 Pandas 的索引)?(因为城市名称超过 300 个,横着排不下)。
3 个回答
2
在matplotlib
中,处理这个问题的方法是使用MutlipLocator
。第二种方法也很简单明了。
from matplotlib.ticker import *
plt.plot(range(10))
ax=plt.gca()
ax.yaxis.set_major_locator(MultipleLocator(0.5))
plt.xticks(range(10), list('ABCDEFGHIJ'), rotation=90) #would be range(3xx), List_of_city_names, rotation=90
plt.savefig('temp.png')
2
对于第一个问题,可以添加:
plt.yticks(np.arange(0,1+0.1,0.1))
关于第二个问题,我在matplotlib的示例库里找到了这个:
ticks_and_spines 示例代码1
经过一些研究,我发现没有一个“原生”的Seaborn解决方案,于是我根据@Pablo Reyes和@CT Zhu的建议,结合matplotlib的函数,写出了下面的代码:
from matplotlib.ticker import *
figure(num=None, figsize=(20, 10))
plt.title('Cumulative Distribution Function for ALABAMA population')
plt.xlabel('City')
plt.ylabel('Percentage')
plt.plot(al_df.pop_cum_perc)
#set the tick size of y axis
ax = plt.gca()
ax.yaxis.set_major_locator(MultipleLocator(0.1))
#set the labels of y axis and text orientation
ax.xaxis.set_major_locator(MultipleLocator(10))
ax.set_xticklabels(labels, rotation =90)
这个解决方案引入了一个新的元素“labels”,我需要在绘图之前指定它,这个“labels”是从我的Pandas数据框中创建的一个新的Python列表:
labels = al_df.NAME.values[:]
这样就生成了下面的图表:

不过这需要一些调整,因为如果我像这样指定显示Pandas数据框中的每个城市:
ax.xaxis.set_major_locator(MultipleLocator(1))
就会产生一个根本无法阅读的图表(只显示x轴):
