从pandas datafram绘制和格式化seaborn图表

2024-03-28 19:31:25 发布

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

我有一个熊猫数据框al_df,它包含了美国最近一次人口普查中阿拉巴马州的人口。我创建了一个使用seaborn绘制的累积函数,得到了以下图表:

CDF for the population of Alabama

与绘图相关的代码如下:

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) 如何更改刻度,以便yaxis每0.1个单位显示一条网格线,而不是显示默认的0.2? 2) 如何更改x轴以显示垂直绘制的城市的实际名称,而不是城市的“等级”(来自熊猫索引)?(有300多个名字,所以横向上不太合适)。


Tags: 数据函数代码none绘图df图表绘制
3条回答

经过一番研究,并没有找到一个“本地”的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”,我必须在绘图之前指定它,它是从我的Pandas数据框创建的一个新的Python列表:

labels = al_df.NAME.values[:]

制作下表: enter image description here

这需要进行一些调整,因为在pandas数据框中指定每个城市的显示,如下所示:

ax.xaxis.set_major_locator(MultipleLocator(1))

生成无法读取的图表(仅显示x轴): enter image description here

对于问题1),添加:

plt.yticks(np.arange(0,1+0.1,0.1))

问题2),我在matplotlib库中找到了这个: ticks_and_spines example code

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')

enter image description here

相关问题 更多 >