Python 根据剖面标签(pandas/matplotlib)更改饼图的颜色
我在一个名为Python 根据剖面标签(pandas/matplotlib)更改饼图的颜色,python,pandas,matplotlib,colors,pie-chart,Python,Pandas,Matplotlib,Colors,Pie Chart,我在一个名为plot_df的数据框中工作,该数据框如下所示: 我正在尝试创建u数量的饼图子图。这是我目前的代码: fig, axes = plt.subplots(nrows=int(np.ceil(plot_df.index.get_level_values(0).nunique()/3)), ncols=3, figsize=(15,15)) fig.tight_layout() axe
plot_df
的数据框中工作,该数据框如下所示:
我正在尝试创建u数量的饼图子图。这是我目前的代码:
fig, axes = plt.subplots(nrows=int(np.ceil(plot_df.index.get_level_values(0).nunique()/3)),
ncols=3,
figsize=(15,15))
fig.tight_layout()
axes_list = [item for sublist in axes for item in sublist]
for country in plot_df.index.get_level_values(0).unique():
ax = axes_list.pop(0)
plot_df.loc[(country, slice(None))].plot(kind='pie',
subplots=True,
legend=False,
autopct='%1.1f%%',
ax=ax)
ax.set_title(country, fontweight='bold')
ax.tick_params(
bottom=False
)
ax.set_ylabel(ylabel=None)
for ax in axes_list:
ax.remove()
我的最终结果如下所示:
我的问题与分配给每种视觉格式的颜色有关。每个国家都有不同的格式,这会导致标签颜色分配不一致。(例如,数字在香港是蓝色的,但在印度是绿色的)。
有没有办法创建一个字典,以可视格式作为键,以颜色作为值,并将此字典指定给pandas plotcolor参数?谢谢。您可以对饼图使用
colors
参数。因为这需要一个数组,所以必须为每个绘图创建一个与输入数据相对应的数组
cdict = {'DIGITAL': 'r', 'DIGIMAX3D': 'y', 'DIGITAL3D': 'b', ...}
for country in plot_df.index.get_level_values(0).unique():
ax = axes_list.pop(0)
df = plot_df.loc[(country, slice(None))]
colors = [cdict[x] for x in df.index] % colors based on index of input data
df.plot(kind='pie', colors=colors, subplots=True, legend=False, autopct='%1.1f%%', ax=ax)
您可以做的另一件事是重塑数据并使用熊猫绘图:
(df['$'].unstack(0,fill_value=0)
.plot.pie(subplots=True, layout=(4,4), figsize=(12,12))
);
输出:
不要包含数据的图片。复制/粘贴文本到问题中。@QuangHoang我的数据是SQL查询及其多索引的结果,因此我认为最好将其显示为png,而不是重新创建。您可以始终执行
打印(df.reset_index())
并将其复制到此处。比图像好多了。更多
(df['$'].unstack(0,fill_value=0)
.plot.pie(subplots=True, layout=(4,4), figsize=(12,12))
);