(python matplotlib)如何更改棒棒糖图中每个棒棒糖的颜色(斧杆)

2024-09-27 02:20:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用ax.stem在python中绘制棒棒糖图。然而,我发现很难给每个棒棒糖指定不同的颜色 as shown here

如您所见,我有两个类别“GWP”和“FDP”。 在我的项目中,每一个类别都应该分为4个子类别“成分”、“废物”、“能源”和“基础设施”。因此,我想给它们分配不同的颜色来表示子类别。在

这里有一个解决方案:https://python-graph-gallery.com/181-custom-lollipop-plot/

但这只教你如何改变所有棒棒糖的颜色。在

还有另一个解决方案:https://python-graph-gallery.com/183-highlight-a-group-in-lollipop/

但这个并没有真正使用ax.stem。在

请告诉我如何给每个棒棒糖指定不同的颜色。在

(同时,我也不知道为什么我的情节被颠倒了。另外,y轴没有按顺序对齐,并且有一个点没有通过直线连接。但它在我的原始图中显示正确。)

这是我的代码:

#%%
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

plt.style.use('ggplot')


# my dataset
columns = np.array(['types', 'GWP100 (year)', 'FDP (year)'])


types = np.array(['Total (ingredient) per kg', 'Total (waste) per kg',
       'energy (whole process) per kg', 'Infrastructure', 'Total (Total)']).reshape(5,1)
gwp = np.array([  2.86982617e+02,   2.16824983e+02,   4.38920760e+01,
         6.02400000e-02,   5.47759916e+02]).reshape(5,1)
fdp = np.array([  1.35455867e+02,   7.02868322e+00,   1.26622560e+01,
         1.64568000e-02,   1.55163263e+02]).reshape(5,1)

original_data = np.concatenate((types, gwp, fdp), axis = 1)




# produce dataframe
data = pd.DataFrame(original_data, columns = columns)

#                           types GWP100 (year)  FDP (year)
#0      Total (ingredient) per kg    286.982617  135.455867
#1           Total (waste) per kg    216.824983  7.02868322
#2  energy (whole process) per kg     43.892076   12.662256
#3                 Infrastructure       0.06024   0.0164568
#4                  Total (Total)    547.759916  155.163263


#%%  graph
fig = plt.figure(1, figsize =(8,6))

# 1st subplot
ax1 = fig.add_subplot(1,2,1)
gwp = data[data.columns[1]]

ax1.stem(gwp)
ax1.set_ylabel(r'kg CO$_2$-Eq', fontsize=10)
ax1.set_xlabel('GWP', fontsize=10)


# 2nd subplot
ax2 = fig.add_subplot(1,2,2)
fdp = data[data.columns[2]]

ax2.stem(fdp)
ax2.set_ylabel(r'kg oil-Eq', fontsize = 10)
ax2.set_xlabel('FDP', fontsize=10)

Tags: columnsdata颜色asnp类别arrayyear
2条回答

stem当前由两条线和一条由顶部的点组成的“线”。它不能选择在其接口内分别对行进行着色。在

你可以复制干图,用你喜欢的颜色手工画线。在

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

columns = np.array(['types', 'GWP100 (year)', 'FDP (year)'])
types = np.array(['Total (ingredient) per kg', 'Total (waste) per kg',
       'energy (whole process) per kg', 'Infrastructure', 'Total (Total)'])
gwp = np.array([  2.86982617e+02,   2.16824983e+02,   4.38920760e+01,
         6.02400000e-02,   5.47759916e+02])
fdp = np.array([  1.35455867e+02,   7.02868322e+00,   1.26622560e+01,
         1.64568000e-02,   1.55163263e+02])

# produce dataframe
data = pd.DataFrame([types,gwp,fdp], index = columns).transpose()

colors = list("bgryk")

fig, (ax, ax2) = plt.subplots(ncols=2)

for t, y, c in zip(data["types"], data["GWP100 (year)"],colors):
    ax.plot([t,t], [0,y], color=c, marker="o", markevery=(1,2))
ax.set_ylim(0,None)
plt.setp(ax.get_xticklabels(), rotation=90)
fig.tight_layout()    
plt.show()

enter image description here

当然,更有效的解决方案是将LineCollection与点的散点图结合使用。在

^{pr2}$

我将回答你的一个主要问题,关于相同的颜色线和标记分类。在调用ax1.stem()以根据正式文档指定颜色列表时,似乎没有直接选项。事实上,他们说,如果一个人这样做,结果可能是不合理的。尽管如此,下面是一个让事情按你的方式完成的技巧。在

想法如下:

  • 获取子图上显示的对象(stemline
  • 获取标记的x-y数据
  • 循环数据并更改每个茎线的颜色。用同一个记号画出相同的颜色。colors是一个数组,指定您选择的颜色。在

以下是本规范的相关部分:

# 1st subplot
ax1 = fig.add_subplot(1,2,1)
gwp = data[data.columns[1]]

colors = ['r', 'g', 'b', 'y', 'k']
_, stemlines, _ = ax1.stem(gwp)

line = ax1.get_lines()
xd = line[0].get_xdata()
yd = line[0].get_ydata()

# mec and mfc stands for markeredgecolor and markerfacecolor
for i in range(len(stemlines)):
    plt.plot([xd[i]], [yd[i]], 'o', ms=7, mfc=colors[i], mec=colors[i])
    plt.setp(stemlines[i], 'color', colors[i])

ax1.set_ylabel(r'kg CO$_2$-Eq', fontsize=10)
ax1.set_xlabel('GWP', fontsize=10)


# 2nd subplot
ax2 = fig.add_subplot(1,2,2)
fdp = data[data.columns[2]]

_, stemlines, _ = ax2.stem(fdp)

line = ax2.get_lines()
xd = line[0].get_xdata()
yd = line[0].get_ydata()

for i in range(len(stemlines)):
    plt.plot([xd[i]], [yd[i]], 'o', ms=7, mfc=colors[i], mec=colors[i])
    plt.setp(stemlines[i], 'color', colors[i])

enter image description here

相关问题 更多 >

    热门问题