Python 突出显示某些条形图标签
所以我有这个水平条形图,我想用其他颜色突出显示某些标签(或关键字)。 这是我的水平条形图: 我想让关键字“自然”和“全景”变成红色。我尝试了此代码,但不起作用:Python 突出显示某些条形图标签,python,matplotlib,Python,Matplotlib,所以我有这个水平条形图,我想用其他颜色突出显示某些标签(或关键字)。 这是我的水平条形图: 我想让关键字“自然”和“全景”变成红色。我尝试了此代码,但不起作用: f, ax = plt.subplots(figsize=(15,15)) plt.autoscale(enable=True, axis='y', tight=True) # tight layout plt.barh(df['keywords'], df['number'])
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')
您可以尝试添加两列,即“数字\红色”和“数字\蓝色”:
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)
“数字\红色”仅显示属于“全景”或“自然”的数字,而用零填充关键字的数字数字“蓝色”的作用正好相反。(您可以打印df以查看)
因此,如果在条形图中覆盖这两列:
plt.barh(df['keywords'],df['number_red'], color='red')
plt.barh(df['keywords'],df['number_blue'], color='blue')
数字将是互补的,但会显示所需的颜色。我希望这有帮助 这回答了你的问题吗?实际上不是。因为它占据了标签的位置,而我想根据关键字突出显示标签。我将最后两个代码更改为
plt.barh(df['number\u red'],df['number'],color='red')
,这样它就可以在右边的列中绘制标签。但是y轴现在显示的是数字,而不是关键字。嗨,我更改了答案中的最后两个代码,所以它应该将“关键字”列设置为条形码名称。(而之前的代码将整数(0,1,2…)设置为条形图名称)。请让我知道它现在是否有效!的确@tianlinhe。。。它现在运行得很好。谢谢