【问题标题】:pandas plot x axis labels overlapping [duplicate]熊猫绘制x轴标签重叠[重复]
【发布时间】:2019-10-01 21:57:51
【问题描述】:
import matplotlib.pyplot as plt
import pandas as pd
from PIL import Image
import numpy as np
#code here

df = pd.DataFrame(items) #items is a list of dictionaries
counts =df.groupby('Merchant')['Merchant 1'].count().sort_values(ascending=False)counts2 =df.groupby('Merchant 2')['Seller'].count().sort_values(ascending=False)
total = counts.add(counts2, fill_value=0)
plt.ylabel('Number')
plt.xlabel("Merchant")
plt.title('Merchants Overview',color='b')
total.plot(kind='bar')
plt.xticks(rotation='horizontal')
plt.savefig("ex")

提供正确的“条”,但文本在 x 轴上重叠

另一个快速的问题,如何将条形从高到低排序。

我检查了这个Pandas plot hide some x-axis labels,还有x axis label in plot overlaps 这是我的第一个问题,请多多关照。

【问题讨论】:

  • 正确的方法是使用rot=参数:total.plot(kind='bar', rot=...)如复制所示。

标签: python pandas


【解决方案1】:

尝试改变:

total.plot(kind='bar')
plt.xticks(rotation='horizontal')

total.sort_values(ascending=False).plot(kind='bar')
plt.xticks(rotation=90)

输出:

或者:

counts.sort_values(ascending=False).plot(kind='bar', color='darkblue')
plt.xticks(rotation=25)

输出:

如果你真的坚持横标,考虑横条:

counts.sort_values(ascending=False).plot(kind='barh', color='darkblue')
# plt.xticks(rotation=25)

输出:

【讨论】:

  • 这是否使 x 标签垂直(在您的图像中)?我想让它们保持水平
  • 是的,这要好得多,但没有办法将条隔开,以便文本占用空间(扩大条的空间或类似的东西)
  • 在这种情况下,尝试通过在任何绘图/标签之前添加 plt.figure(figsize=(20,5)) 来玩 figsize。但标签可能太小而无法阅读。
猜你喜欢
  • 2016-04-10
  • 2021-12-09
  • 1970-01-01
  • 1970-01-01
  • 2017-01-14
  • 2017-01-31
  • 2017-09-20
  • 2014-04-30
  • 2017-06-03
相关资源
最近更新 更多