types = df['type'].unique() labels = types.tolist() fig = plt.figure(figsize=(8, 6)) ax = plt.subplot(111) b_num = np.arange(0, 10.5, 0.5) for t in types: ax.hist(df.loc[df['type'] == t, 'rating'], bins=b_num, rwidth=0.9, alpha=0.6, label=t, ) ax.legend() ax.set_xlabel('rating') ax.set_ylabel(r'Count(rating)') plt.show()重叠绘制直方图,输出效果达到每个间距的值是累加后的值
时间: 2023-12-12 16:04:36 浏览: 34
要实现每个间距的值是累加后的值,可以在循环中统计各个type的直方图数据,并将数据进行累加。然后将累加后的数据绘制为堆积直方图,示例代码如下:
```python
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# 生成数据
df = pd.DataFrame({
'type': ['A', 'B', 'A', 'C', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C'],
'rating': [7.5, 8.2, 9.1, 6.7, 7.8, 8.5, 7.2, 8.9, 6.6, 8.3, 8.1, 7.4]
})
# 统计各个type的直方图数据,并将数据进行累加
types = df['type'].unique()
labels = types.tolist()
b_num = np.arange(0, 10.5, 0.5)
hist_data = []
for t in types:
hist, bins = np.histogram(df.loc[df['type'] == t, 'rating'], bins=b_num)
hist_data.append(hist)
hist_data = np.vstack(hist_data)
hist_data = np.cumsum(hist_data, axis=0)
# 绘制堆积直方图
fig = plt.figure(figsize=(8, 6))
ax = plt.subplot(111)
for i, t in enumerate(types):
ax.bar(b_num[:-1], hist_data[i], label=t, alpha=0.6)
ax.legend()
ax.set_xlabel('rating')
ax.set_ylabel(r'Count(rating)')
plt.show()
```
其中,`hist, bins = np.histogram(df.loc[df['type'] == t, 'rating'], bins=b_num)`用于统计各个type的直方图数据,`hist_data.append(hist)`将直方图数据进行累加,`hist_data = np.vstack(hist_data)`将数据转换为二维数组,`hist_data = np.cumsum(hist_data, axis=0)`将数据进行累加。最后使用`ax.bar(b_num[:-1], hist_data[i], label=t, alpha=0.6)`绘制堆积直方图。