【问题标题】:Histogram color by class按类别划分的直方图颜色
【发布时间】:2018-04-25 07:53:45
【问题描述】:

我有一个带有 2 列“高度”和“类”的熊猫数据框,类是具有 3 个值 1,2 和 5 的列。 现在我想按类制作高度数据和颜色的直方图。 plot19_s["vegetation height"].plot.hist(bins = 10)

这是我的直方图

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

【问题讨论】:

标签: python matplotlib


【解决方案1】:

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

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()

【讨论】:

  • 谢谢,是否可以交换 x 和 y 轴。使频率位于 x 轴上。
  • 是的,您需要将bar 替换为barh,将width 替换为height,将bottom 替换为left
猜你喜欢
  • 2010-12-11
  • 2014-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-22
  • 1970-01-01
  • 2020-12-07
  • 1970-01-01
相关资源
最近更新 更多