【问题标题】:plotting & formatting seaborn chart from pandas dataframe从 pandas 数据框中绘制和格式化 seaborn 图表
【发布时间】:2014-06-03 08:28:51
【问题描述】:

我有一个 pandas 数据框 al_df,其中包含最近美国人口普查中阿拉巴马州的人口。我创建了一个使用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 个名称,因此它们不能很好地横向排列)。

【问题讨论】:

  • plt从何而来?
  • 我不完全理解你的问题。 Seaborn 构建在 matplotlib 之上,因此您可以使用 import matplotlib.pyplot as plt 访问 seaborn 图表的元素,就像上面的示例中一样
  • 对不起!您的代码中没有任何导入行,所以我想知道您是如何导入 plt.你是作为 matplotlib.plt 还是 seaborn.plt 导入的。

标签: python matplotlib pandas seaborn


【解决方案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)

解决方案引入了一个新元素“标签”,我必须在绘图之前指定它,作为从我的 Pandas 数据框创建的新 Python 列表:

labels = al_df.NAME.values[:]

制作如下图表:

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

ax.xaxis.set_major_locator(MultipleLocator(1))

生成无法阅读的图表(仅显示 x 轴):

【讨论】:

  • 我为我的数据框尝试了你的方法,但它不起作用,也许我弄错了?我有三列的数据框,一列是学生的姓名,另外两列是每个学生的错误和正确答案的数量。所以我想可视化每个学生的答案重新分配。但不是像你这样的图片,我只有空的人物,第一个学生作为标签,没有任何曲线。为什么会发生?
  • 我的脚本看起来像``` plt.plot(df.FALSE_ANSWER) #设置y轴刻度的大小 ax = plt.gca() ax.yaxis.set_major_locator(MultipleLocator(0.1)) 标签= df.name_of_student[:] #设置y轴和文本方向的标签 ax.xaxis.set_major_locator(MultipleLocator(10)) ax.set_xticklabels(labels, rotation =90) ```
  • @very_young 我认为累积图表不适用于您的数据(至少,它对我没有意义)。您为什么不发布一个引用此答案的新问题?这样,您可以从其他人那里获得一些高质量的答案,包括我将为您发布的答案。发送。
【解决方案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')

【讨论】:

    【解决方案3】:

    对于问题1),添加:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-21
      • 2020-04-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-13
      • 1970-01-01
      • 1970-01-01
      • 2021-01-15
      相关资源
      最近更新 更多