【问题标题】:matplotlib.pyplot overlaying axis labels on barsmatplotlib.pyplot 在条形图上覆盖轴标签
【发布时间】:2023-03-14 04:12:01
【问题描述】:

我有这段代码可以生成这个图表,但是文本非常糟糕。我尝试了水平和垂直调整和旋转以使其可读,但没有成功。

有人可以告诉我如何重新定位文本并选择更好的字体/大小以便它们可读吗?

非常欢迎任何有关用于显示此数据的更好图表的建议。

import matplotlib.pyplot as plt

N = 13
ind = np.arange(N) 
width = 0.8

good=[0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48]
bad=[0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48]
keys=[u'gaming', u'recreation', u'business', u'computer_internet', u'unknown', u'culture_politics', u'science_technology', u'law_crime', u'sports', u'religion', u'weather', u'health', u'arts_entertainment']
c2='r'
c1='b'
p1 = plt.bar(ind, good, width, color=c1)
p2 = plt.bar(ind, bad, width, color=c2, bottom=good)

plt.ylabel('Number of URLs scanned')
plt.title('Category')
plt.xticks(ind+width/2., keys, rotation='vertical')
#plt.yticks(np.arange(0,81,10), rotation='vertical')
plt.legend( (p1[0], p2[0]), ('good', 'bad') )

plt.show()

【问题讨论】:

  • 你能解释一下你所说的“非常糟糕”是什么意思吗?只是保存图的时候被剪掉了?
  • 不,即使在底部看到,它也太长并且使图表看起来不完整。我不知道我们是否可以将标签垂直移动到条形旁边?

标签: python matplotlib


【解决方案1】:

您可以尝试使用水平条形图。它通常更适合这种可视化。我还进行了一些调整以对类别进行排序并使用更好的颜色:

import numpy
import matplotlib.pyplot as plt

good = np.array([0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48])
bad = np.array([0, 1, 28, 144, 0, 41, 23, 5, 7, 2, 3, 9, 48])
keys = np.array([u'gaming', u'recreation', u'business', u'computer_internet',
                 u'unknown', u'culture_politics', u'science_technology',
                 u'law_crime', u'sports', u'religion', u'weather',
                 u'health', u'arts_entertainment'])
ind = np.arange(1, len(keys) + 1) 

order = np.argsort(good + bad)
good, bad, keys = good[order], bad[order], keys[order]

c2 = '#FF7777'
c1 = '#7777FF'
p1 = plt.barh(ind, good, color=c1, align="center", label="good")
p2 = plt.barh(ind, bad, color=c2, left=good, align="center", label="bad")

plt.xlabel('Number of URLs scanned')
plt.yticks(ind, keys)
plt.legend(loc="center right")
plt.tight_layout()

【讨论】:

    【解决方案2】:

    尝试以下方法来调整下边距:

    plt.tight_layout()fig.savefig(bbox_inches='tight') 尝试让 matplotlib 自行修复。

    您可以手动调整边距

    #adjust these as needed
    plt.subplots_adjust(bottom=0.1, top=0.9, left=0.05, right=0.95)
    

    编辑:

    如果您希望将标签放在条形旁边的图上,您可以执行类似的操作

    N = 13
    width = 0.4
    ind = np.arange(N) + 0.5 #this puts the bars on the right of each "bin"
    p1 = plt.bar(ind, good, width, color=c1)
    p2 = plt.bar(ind, good, width, color=c2, bottom=good)
    for rect, key in zip(p1, keys):
        x, y = rect.get_xy()
        plt.text(x-width, y, text, va='bottom', ha='left', rotation=90)
    

    您可能希望在 y 坐标上添加一点缓冲区(例如 y+0.01 或其他东西)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-07-24
      • 2022-01-07
      • 2021-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-02-18
      相关资源
      最近更新 更多