按类别的直方图颜色

2024-10-03 11:13:42 发布

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

我有一个pandas数据帧,有两列“height”和“class,class是一列,有3个值1、2和5。 现在我想按类生成高度数据和颜色的柱状图。plot19_s["vegetation height"].plot.hist(bins = 10)

这是我的直方图

但是现在我想通过直方图中颜色的变化来查看不同的类。在


Tags: 数据pandas高度plot颜色直方图histclass
1条回答
网友
1楼 · 发布于 2024-10-03 11:13:42

由于我不确定潜在的重复是否真的回答了这里的问题,这是一种使用numpy.histogram和matplotlib barplot生成堆积直方图的方法。在

import pandas as pd
import numpy as np;np.random.seed(1)
import matplotlib.pyplot as plt

df = pd.DataFrame({"x" : np.random.exponential(size=100),
                   "class" : np.random.choice([1,2,5],100)})

_, edges = np.histogram(df["x"], bins=10)
histdata = []; labels=[]
for n, group in df.groupby("class"):
    histdata.append(np.histogram(group["x"], bins=edges)[0])
    labels.append(n)

hist = np.array(histdata) 
histcum = np.cumsum(hist,axis=0)

plt.bar(edges[:-1],hist[0,:], width=np.diff(edges)[0],
            label=labels[0], align="edge")

for i in range(1,len(hist)):
    plt.bar(edges[:-1],hist[i,:], width=np.diff(edges)[0],
            bottom=histcum[i-1,:],label=labels[i], align="edge")

plt.legend(title="class")
plt.show()

enter image description here

相关问题 更多 >