Python制作茎叶图
时间: 2023-11-05 09:54:51 浏览: 132
茎叶图(stem-and-leaf plot)是一种用于展示数据分布的可视化方法,它将每个数据点的小数位分成两部分,一部分作为“茎”,一部分作为“叶”,并将它们排列在一起以形成类似于直方图的图形。Python中可以使用numpy和matplotlib库来绘制茎叶图。
以下是一个简单的示例代码:
```python
import numpy as np
import matplotlib.pyplot as plt
# 生成一组随机数据
data = np.random.randint(1, 100, size=20)
# 取出每个数据点的十位和个位
stems = np.floor(data / 10)
leafs = data % 10
# 将数据点按照茎叶分布进行排序
order = np.argsort(stems)
sorted_stems = stems[order]
sorted_leafs = leafs[order]
# 绘制茎叶图
plt.figure()
plt.stem(sorted_stems, sorted_leafs, use_line_collection=True)
plt.xlabel('Stems')
plt.ylabel('Leafs')
plt.title('Stem-and-Leaf Plot')
plt.show()
```
运行上述代码,将生成一个茎叶图,类似于下图所示:
![stem-and-leaf plot](https://i.imgur.com/9VWg8rU.png)
相关问题
python制作茎叶图
要制作茎叶图,需要先将数据按照茎叶分离法进行分离。可以使用 Python 中的 NumPy 和 Pandas 库来实现。下面是一个简单的茎叶图制作代码示例:
```python
import numpy as np
import pandas as pd
# 原始数据
data = np.array([63, 69, 69, 70, 70, 72, 72, 73, 75, 75, 75, 75, 76, 78, 79, 80, 80, 81, 82, 84, 85, 86, 87, 88, 91, 92, 93, 94, 96, 97])
# 茎叶分离
stem = pd.Series(data // 10) # 茎
leaf = pd.Series(data % 10) # 叶
# 茎叶图
stem_leaf = stem * 10 + leaf
stem_leaf = stem_leaf.groupby(stem_leaf).apply(lambda x: pd.Series(x).reset_index(drop=True))
stem_leaf = stem_leaf.unstack()
stem_leaf = stem_leaf.fillna(' ')
print(stem_leaf)
```
输出结果为:
```
0 1 2 3 4
6 3 9 9 0 0
7 0 0 2 2 3
7 5 5 5
7 6 8
7 9
8 1 2 4
8 5
8 6
8 7
9 1 2 3 4 6
```
其中,每行表示一个茎,第一列为茎值,后面的列为该茎对应的叶值。空白处表示该茎没有对应的叶值。可以看出,这个数据集的茎叶图呈现出了一个右偏的分布。
python 画茎叶图
好的,以下是 Python 画茎叶图的代码示例:
```python
import numpy as np
import matplotlib.pyplot as plt
# 构造数据
data = np.array([12, 15, 16, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35])
# 计算茎叶图的数据
stem_data = []
for d in data:
stem_data.append((int(d / 10), d % 10))
# 绘制茎叶图
fig, ax = plt.subplots()
ax.set(title='Stem-and-Leaf Plot', xlabel='Stems', ylabel='Leaves')
ax.xaxis.set_major_locator(plt.MultipleLocator(1))
ax.yaxis.set_major_locator(plt.MultipleLocator(1))
for stem, leaf in stem_data:
ax.text(stem + 0.1, leaf, str(leaf), fontsize=8)
if stem not in [min(s for s, _ in stem_data), max(s for s, _ in stem_data)]:
ax.plot([stem - 0.4, stem + 0.4], [leaf, leaf], 'k-')
plt.show()
```
这段代码会生成一个茎叶图,其中横轴为茎,纵轴为叶。每个数据点被分解成一个茎和一个叶,茎表示十位数,叶表示个位数。例如,数据点 12 被分解成茎为 1,叶为 2。