Circlify - 改变其中一个圆圈的颜色

Circlify - change the colour of just one of the circles

我有这个代码:

import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame({
    'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
    'Value': [10, 2, 23, 87, 12, 65]
})


circles = circlify.circlify(
    df['Value'].tolist(), 
    show_enclosure=False, 
    target_enclosure=circlify.Circle(x=0, y=0, r=1)
)

# Create just a figure and only one subplot
fig, ax = plt.subplots(figsize=(10,10))

# Title
ax.set_title('Basic circular packing')

# Remove axes
ax.axis('off')

# Find axis boundaries
lim = max(
    max(
        abs(circle.x) + circle.r,
        abs(circle.y) + circle.r,
    )
    for circle in circles
)
plt.xlim(-lim, lim)
plt.ylim(-lim, lim)

# list of labels
labels = df['Name']

# print circles
for circle, label in zip(circles, labels):
    x, y, r = circle
    ax.add_patch(plt.Circle((x, y), r, alpha=0.2, linewidth=2,color='#e6d4ff'))
    plt.annotate(
          label, 
          (x,y ) ,
          va='center',
          ha='center',
          size=12
     )

它产生这个输出:

我只想更改其中一个圆圈的颜色(例如,最大的圆圈)。

我尝试更改颜色:

color='#e6d4ff'

例如,颜色列表:

color=['#e6d4ff','#e6d4ff','#e6d4ff','#e6d4ff','#e6d4ff','#ffc4c4']

错误:

RGBA sequence should have length 3 or 4

我猜错误是说如果我提供了一个列表,那么该列表应该只是 RGB 维度。

有人可以给我看看吗? (我在 python 图片库中看不到它,例如 [here][2] 或 circlify 文档 here 但也许我错过了它?)

在每次调用 plt.Circle(...) 时,您只会创建一个圆圈,它只有一种颜色。要为不同的圆圈分配不同的颜色,可以将颜色添加到 for 循环中,例如: for circle, label, color in zip(circles, labels, colors):.

请注意,circlify 需要按排序顺序排列的值列表,并且返回的列表包含从小到大排序的圆圈。在您的示例代码中,D 是最大的圆圈,但在您的图中,您将其标记为 F。在开始时对数据帧进行排序并使用该顺序有助于保持值和标签同步。

这里是示例代码,D 最大,颜色不同(代码也 更一致):

import matplotlib.pyplot as plt
import pandas as pd
import circlify

df = pd.DataFrame({'Name': ['A', 'B', 'C', 'D', 'E', 'F'],
                   'Value': [10, 2, 23, 87, 12, 65]})
df = df.sort_values('Value')  # the order is now ['B', 'A', 'E', 'C', 'F', 'D']
circles = circlify.circlify(df['Value'].tolist(),
                            show_enclosure=False,
                            target_enclosure=circlify.Circle(x=0, y=0, r=1))

fig, ax = plt.subplots(figsize=(10, 10))

ax.set_title('Basic circular packing')
ax.axis('off')
ax.set_aspect('equal')  # show circles as circles, not as ellipses

lim = max(max(abs(circle.x) + circle.r, abs(circle.y) + circle.r, )
          for circle in circles)
ax.set_xlim(-lim, lim)
ax.set_ylim(-lim, lim)

labels = df['Name']  # ['B', 'A', 'E', 'C', 'F', 'D']
colors = ['#ffc4c4' if val == df['Value'].max() else '#e6d4ff' for val in df['Value']]
for circle, label, color in zip(circles, labels, colors):
    x, y, r = circle
    ax.add_patch(plt.Circle((x, y), r, alpha=0.7, linewidth=2, color=color))
    ax.annotate(label, (x, y), va='center', ha='center', size=12)
plt.show()