Python/Pandas对step函数中的数据点使用不同的颜色

2024-04-25 19:18:26 发布

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

我一直在尝试使用Matplotlib Step函数绘制pandas数据帧的一部分。但是,我无法基于属于该实例的其他类别对单个数据点或“步骤”着色。你知道吗

确切地说,我想创建一个价值顺序图,将运营成本与产能的关系绘制为单步图。你知道吗

新代码

df = pd.read_csv("merit_v1.csv")
df = df[df.energy_source != "Hydro"]

df = df.sort_values(by="margC",ascending=True)

df["capacity"] = round(df["capacity"].cumsum() / 1000, 3)
y = df["margC"].tolist()
x = df["capacity"].tolist()

x_app = x[1:] 
y_app = y[:len(y)-1]

x = x + x_app + [0]
y = y + y_app + [y[0]]

x = sorted(x)
y = sorted(y)

colors = []
energy = df["energy_source"].tolist()
for item in energy:
    if item == "Nuclear":
            color = "#DDF45B"
    if item == "Coal":
            color = "#141115"
    if item == "Lignite":
            color = "#8D6346"
    if item == "Bioenergy":
            color = "#5A720F"
    if item == "Natural Gas":
            color = "#4C2B36"
    if item == "Oil":
            color = "#C1A5A9"
    colors.append(color)

colors = list(np.repeat(colors, 2))

points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)

fig, ax = plt.subplots()

lc = LineCollection(segments, color = colors)

lc.set_linewidth(2)
line = ax.add_collection(lc)

ax.set_xlim(-5, max(x) + 5)
ax.set_ylim(0, max(y) + 5)

ax.fill_between(x,y, facecolor="w")
ax.set_title("Merit-Order des europäischen Kraftwerkparks")
ax.set_xlabel('Kummulierte Leistung GW')
ax.set_ylabel('Grenzkosten €/MWh')
plt.show()

Tags: appdfifnp绘制axitempoints