简体   繁体   English

Matplotlib 堆叠 plot 数据不均匀

[英]Matplotlib stacked plot with uneven data

I'd like to plot a stacked histogram plot, but I have data columns of uneven size, and indeed data type:我想 plot 堆叠直方图 plot,但我有大小不均匀的数据列,并且确实是数据类型:

bovine_eta = bovine['Emissivity'].dropna()
equine_eta = equine['Emissivity'].dropna()
ovine_eta =  ovine['Emissivity'].dropna()

bovine_eta.sort()
equine_eta.sort()
ovine_eta.sort()


print(bovine_eta)
['0.93' '0.93' '0.93' '0.95' '0.95' '0.95' '0.95' '0.95' '0.95' '0.95' 
 '0.95' '0.95' '0.95' '0.95' '0.95' '0.95' '0.96' '0.96' '0.97' '0.97'
 '0.97' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98'
 '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98'
 '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98'
 '0.98' '0.985' '0.985' '0.985' '1']

print(equine_eta)
['0.95' '0.95' '0.95' '0.96' '0.97' '0.97' '0.97' '0.98' '0.98' '0.98', '0.98' '0.99' '0.99']

print(ovine_eta)
['0.95' '0.97' '0.97-0.98' '0.98' '0.98' '0.98' '0.98' '0.98' '0.98', '0.98' '0.98']

I then try然后我尝试

plt.hist([bovine_eta, equine_eta, ovine_eta], stacked=True)

and get the resulting plot:并得到结果 plot: 在此处输入图像描述
This seems very weird, but obviously not far off from what I'd like actually want.这看起来很奇怪,但显然离我真正想要的不远。 How do you fix the x-axis?你如何固定x轴?

The main problem is that all values are strings.主要问题是所有值都是字符串。 For a histogram it helps to convert them to floats.对于直方图,它有助于将它们转换为浮点数。 A next problem is that the third entry of ovine is a string that can't be converted to a float.下一个问题是ovine的第三个条目是一个无法转换为浮点数的字符串。 '0.97-0.98' could be replaced by an intermediate value. '0.97-0.98'可以替换为中间值。

As the data is almost discrete, it helps to explicitly provide bin edges aligned with these values.由于数据几乎是离散的,它有助于明确提供与这些值对齐的 bin 边缘。

import matplotlib.pyplot as plt
import numpy as np

bovine_eta = ['0.93','0.93','0.93','0.95','0.95','0.95','0.95','0.95','0.95','0.95','0.95','0.95','0.95','0.95','0.95','0.95','0.96','0.96','0.97','0.97','0.97','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.985','0.985','0.985','1']
equine_eta = ['0.95','0.95','0.95','0.96','0.97','0.97','0.97','0.98','0.98','0.98', '0.98','0.99','0.99']
ovine_eta = ['0.95','0.97','0.97-0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98','0.98']

ovine_eta[2] = '0.975'  # '0.97-0.98' isn't a valid number

bovine_eta = np.array(bovine_eta, dtype=float)
equine_eta = np.array(equine_eta, dtype=float)
ovine_eta = np.array(ovine_eta, dtype=float)

plt.hist([bovine_eta, equine_eta, ovine_eta],
         bins=np.arange(0.93, 1.01, 0.01),
         stacked=True, label=['bovine', 'equine', 'ovine'])
plt.legend()

堆叠条

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM