jupyter notebook怎么使用双层环形图最内里面数据标签居中
时间: 2024-09-20 15:03:32 浏览: 63
数据分析,画饼图的jupyter notebook
5星 · 资源好评率100%
在Jupyter Notebook中创建双层环形图(donut chart),并且让最内层的数据标签居中,通常可以使用像matplotlib这样的可视化库。以下是一个基本步骤:
首先,确保安装了`matplotlib`库,如果没有,可以通过`pip install matplotlib`来安装。
```python
import matplotlib.pyplot as plt
import numpy as np
# 创建数据
values = [30, 45, 25] # 内层圆环数据
labels = ['A', 'B', 'C'] # 数据标签
angles = [v / sum(values) * 2 * np.pi for v in values] # 计算每个扇区的角度
# 创建图形并绘制第一层环形图(外环)
fig, ax = plt.subplots()
ax.pie(values, labels=labels, autopct='%1.1f%%', startangle=90, wedgeprops=dict(width=0.3)) # 设置外环百分比显示
# 绘制第二层环形图(内环)
core_values = [val * 0.6 for val in values] # 缩小内环数值,便于展示
core_angles = [ang * 0.6 for ang in angles]
core wedges = ax.pie(core_values, radius=0.3, center=ax.get_position().vertices[0], frame=True,
colors=plt.get_cmap('tab20c')(np.arange(len(labels))), labeldistance=1.1, pctdistance=0.85) # 居中设置
# 定义一个函数将内环标签放置在合适的位置
def place_labels(wedges):
for w in wedges:
ang = (w.theta2 - w.theta1)/2. + w.theta1
y = np.sin(np.deg2rad(ang))
x = np.cos(np.deg2rad(ang))
horizontalalignment = {-1: "right", 1: "left"}[int(np.sign(x))]
connectionstyle = "angle,angleA=0,angleB={}".format(ang)
kw = dict(boxstyle="round,pad=0.1", fc=w.color, alpha=0.5, zorder=0, connections={(0,): connectionstyle})
ax.annotate(labels[w.index], xy=(x, y), xytext=(1.35*np.sign(x), 1.4*y),
horizontalalignment=horizontalalignment, **kw)
place_labels(core wedges)
# 显示图表
plt.title("双层环形图")
plt.show()
阅读全文