为了账号安全,请及时绑定邮箱和手机立即绑定

matplotlib 条形图仅突出显示值

matplotlib 条形图仅突出显示值

泛舟湖上清波郎朗 2021-09-14 10:05:45
嗨,我想得到这种条形图。问题是如何通过选择设置相应的xlables?我编码如下以删除不需要的国家/地区标签,但图表也有 nan 作为标签。countries=['United States','Mexico','Japan','China','Korea,Rep.','Ireland','France','Italy']new_index=list(df.index)for i in range(len(new_index)):    if new_index[i] not in countries :        new_index[i]=np.nan这是我的结果,标签中为 nan,条形之间的距离更宽:对于数据:import numpy as npimport pandas as pd#Overall Country listCountries=['United States','Mexico','Japan','China','Korea,Rep.','Ireland','France','Italy','Czech Republic', 'Austria', 'Slovak Republic', 'Slovenia', 'Germany', 'Portugal', 'Hungary', 'Colombia', 'New Zealand', 'Norway', 'Latvia']#Countries to highlightDesired=['United States','Mexico','Japan','China','Korea,Rep.','Ireland','France','Italy']np.random.seed(0)Value=np.random.rand(len(Countries))df = pd.DataFrame({'Countries': Countries,'Value': Value,})df.sort_values(['Value'],inplace=True)df.set_index('Countries',drop=True,inplace=True)ax_1 = df['Value'].plot(kind='bar', title ="graph", figsize=(10, 6), fontsize=12)ax_1.set_xlabel("Country Name", fontsize=12)plt.show()
查看完整描述

1 回答

?
www说

TA贡献1775条经验 获得超8个赞

运行 x-ticks,然后根据countries列表禁用其中的几个。


import numpy as np

import pandas as pd


#Overall Country list

Countries=['United States','Mexico','Japan','China','Korea,Rep.','Ireland','France','Italy','Czech Republic',

 'Austria',

 'Slovak Republic',

 'Slovenia',

 'Germany',

 'Portugal',

 'Hungary',

 'Colombia',

 'New Zealand',

 'Norway',

 'Latvia']


#Countries to highlight

Desired=['United States','Mexico','Japan','China','Korea,Rep.','Ireland','France','Italy']


np.random.seed(0)

Value=np.random.rand(len(Countries))

df = pd.DataFrame({'Countries': Countries,'Value': Value,})

df.sort_values(['Value'],inplace=True)


df.set_index('Countries',drop=True,inplace=True)

ax_1 = df['Value'].plot(kind='bar', title ="graph", figsize=(10, 6), fontsize=12)

ax_1.set_xlabel("Country Name", fontsize=12)




for ticks in ax_1.xaxis.get_major_ticks():

    if ticks.label1.get_text() not in Desired:

        ticks.label1.set_visible(False)

        ax_1.patches[df.index.get_indexer([ticks.label1.get_text()])[0]].set_facecolor('w')

        ax_1.patches[df.index.get_indexer([ticks.label1.get_text()])[0]].set_edgecolor('black')

    else:

        ax_1.patches[df.index.get_indexer([ticks.label1.get_text()])[0]].set_facecolor('r')

        

//img1.sycdn.imooc.com//614003b8000198a507760573.jpg

查看完整回答
反对 回复 2021-09-14
  • 1 回答
  • 0 关注
  • 203 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信