import matplotlib.pyplot as plt import squarify labels = ['A', 'AB', 'ABC', 'ABCD'] sizes = [500, 250, 120, 60] color = ['tomato', 'coral', 'salmon', 'crimson'] # 将颜色改为红色系 squarify.plot(sizes,color=color, label = labels) plt.axis('off') plt.show() 颜色不要固定4个 根据数据自动生成
时间: 2023-08-06 19:19:23 浏览: 51
如果您希望根据数据动态生成颜色,可以使用 Matplotlib 库中的 colormap(颜色映射)功能。例如,可以使用 Matplotlib 的 Reds colormap 将数据转换为红色系:
```python
import matplotlib.pyplot as plt
import squarify
import matplotlib.cm as cm
labels = ['A', 'AB', 'ABC', 'ABCD']
sizes = [500, 250, 120, 60]
# 使用 Blues colormap 将数据转换为蓝色系
cmap = cm.get_cmap('Blues')
color = [cmap(i/len(labels)) for i in range(len(labels))]
squarify.plot(sizes,color=color, label = labels)
plt.axis('off')
plt.show()
```
在这里,我使用 `cm.get_cmap()` 函数获取了 Blues colormap,然后使用列表推导式将每个标签对应的颜色生成到 `color` 列表中。这样,就可以根据数据动态生成颜色了。
需要注意的是,由于 `cmap()` 函数的参数是一个 0 到 1 之间的浮点数,因此在使用列表推导式时需要将 `i` 除以标签数 `len(labels)`,以保证生成的颜色值在 0 到 1 之间。
相关问题
import matplotlib.pyplot as plt import squarify labels = ['A', 'AB', 'ABC', 'ABCD'] sizes = [500, 250, 120, 60] color = ['red', 'green', 'blue', 'orange'] squarify.plot(sizes,color=color, label = labels) plt.axis('off') plt.show() 颜色改成红色系
您可以将“color”列表中的所有颜色改为红色系,例如:
```python
import matplotlib.pyplot as plt
import squarify
labels = ['A', 'AB', 'ABC', 'ABCD']
sizes = [500, 250, 120, 60]
color = ['tomato', 'coral', 'salmon', 'crimson'] # 将颜色改为红色系
squarify.plot(sizes,color=color, label = labels)
plt.axis('off')
plt.show()
```
在这里,我将颜色列表中的颜色改为了“tomato”、“coral”、“salmon”和“crimson”,这些颜色都是红色系中的颜色。您可以根据需要自行选择其他红色系中的颜色。
import networkx as nx import matplotlib.pyplot as plt # 创建图 G = nx.Graph()
# 添加节点
G.add_node(1)
G.add_node(2)
G.add_node(3)
# 添加边
G.add_edge(1, 2)
G.add_edge(2, 3)
G.add_edge(3, 1)
# 绘制图形
nx.draw(G, with_labels=True)
plt.show()