python - matplotlib bar chart with highlights values only
问题描述
Hi I`d like to get a bar chart of this kind. the problem is how to set corresponding xlables by selection?
I coded as follow to delete undesired country labels but the graph has nan as labels as well.
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
And here is my result,with nan in the labels and the distance between bars much wider:
For the data:
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)
plt.show()
解决方案
运行 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')
推荐阅读
- linux - 如何将txt文件附加到先前创建的最后一行
- css - 在 VueJS 组件中加载 SVG 并设置类
- node.js - SQS 队列 - 发送没有 MessageGroupId 的消息?
- python - 安装 OpenCV 4.1 时出错
- hadoop - 纱线 - hadoop 没有正确初始化
- javascript - 加载外部js文件,修改里面的东西然后正常执行
- symfony - Symfony Doctrine 延迟加载 OneToOne 关系中的第二个孩子
- python - 绘图库
- progressive-web-apps - 即使从 Android chrome 浏览器启用 PWA 也不显示通知
- android - OnClickListener 的问题