【问题标题】:Highlight certain barplot label突出显示某些条形图标签
【发布时间】:2020-03-10 16:01:22
【问题描述】:

所以我有这个水平条形图,我想用其他颜色突出显示某些标签(或关键字)。 这是我的水平条形图:

我想让关键字“自然”和“全景”为红色。我试过这段代码,但它不起作用:

f, ax = plt.subplots(figsize=(15,15))
plt.autoscale(enable=True, axis='y', tight=True)                    # tight layout
plt.barh(df['keywords'], df['number'])                              # base barplot with blue color
plt.barh(df[df['keywords']=='nature'], df['number'], color='red')   # overlay barplot with red color
plt.barh(df[df['keywords']=='panorama'], df['number'], color='red') # overlay barplot with red color
ax.tick_params(labelsize=18)
plt.title('Difference average of cluster 3')

【问题讨论】:

标签: python matplotlib


【解决方案1】:

您可以尝试添加两列,即“number_red”、“number_blue”:

df['number_red']=np.where((df['keywords']=='nature')|(df['keywords']=='panorama'),df['number'],0)
df['number_blue']=np.where((df['keywords']!='nature')&(df['keywords']!='panorama'),df['number'],0)

'number_red' 只显示属于'panorama' 或'nature' 的数字,而用零填充关键字的数字。 'number_blue' 则相反。 (你可以打印 df 看看) 因此,如果您只是在条形图中覆盖这两列:

plt.barh(df['keywords'],df['number_red'],  color='red')
plt.barh(df['keywords'],df['number_blue'], color='blue')

这些数字是互补的,但会显示您想要的颜色。我希望这会有所帮助!

【讨论】:

  • 我将最后两个代码更改为plt.barh(df['number_red'], df['number'], color='red'),以便它可以绘制右列。但是 y 轴现在显示的是数字而不是关键字。
  • 您好,我更改了答案中的最后两个代码,以便将“关键字”列设置为栏名称。 (而前面的代码将整数 (0,1,2...) 设置为条形名称)。请让我知道它现在是否有效!
  • 确实是@tianlinhe ...现在效果很好。谢谢
猜你喜欢
  • 2019-07-15
  • 1970-01-01
  • 2022-01-06
  • 2014-04-04
  • 2023-03-10
  • 2019-03-26
  • 2021-03-10
  • 2020-06-23
  • 2019-06-13
相关资源
最近更新 更多