Python 3D散点图颜色图例仅显示第一种颜色。

3
我想创建一个带有尺寸和颜色图例的三维散点图。然而,仅显示列表中第一种颜色的颜色图例。
import matplotlib.pyplot as plt
import matplotlib.colors
# Visualizing 5-D mix data using bubble charts
# leveraging the concepts of hue, size and depth
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
t = fig.suptitle('Wine Residual Sugar - Alcohol Content - Acidity - Total Sulfur Dioxide - Type', fontsize=14)

xs = [1,2,3,5,4]
ys = [6,7,3,5,4]
zs = [1,5,3,9,4]
data_points = [(x, y, z) for x, y, z in zip(xs, ys, zs)]

ss = [100,200,390,500,400]
colors = ['red','red','blue','yellow','yellow']

scatter = ax.scatter(xs, ys, zs, alpha=0.4, c=colors, s=ss)

ax.set_xlabel('Residual Sugar')
ax.set_ylabel('Alcohol')
ax.set_zlabel('Fixed Acidity')


legend1 = ax.legend(*scatter.legend_elements()[0],
                    loc="upper right", title="Classes", labels=colors, bbox_to_anchor=(1.5, 1),prop={'size': 20})
ax.add_artist(legend1)

# produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes", bbox_to_anchor=(1.5, 0.5), prop={'size': 20})

enter image description here

1个回答

1
问题可能是因为matplotlib只接收一个系列进行绘制,因此假定一个图例条目足够。如果我分别制作红色、蓝色和黄色系列的散点图,则所有三个类别都会正确显示在图例中(但在绘制大小时会出现问题)。
也许这不是最优雅的解决方案,但可以手动创建带有类别的图例:
import matplotlib.pyplot as plt
import matplotlib.colors
from matplotlib.lines import Line2D

# Visualizing 5-D mix data using bubble charts
# leveraging the concepts of hue, size and depth
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(111, projection='3d')
t = fig.suptitle('Wine Residual Sugar - Alcohol Content - Acidity - Total Sulfur Dioxide - Type', fontsize=14)

xs = [1,2,3,5,4]
ys = [6,7,3,5,4]
zs = [1,5,3,9,4]
data_points = [(x, y, z) for x, y, z in zip(xs, ys, zs)]

ss = [100,200,390,500,400]
colors = ['red','red','blue','yellow','yellow']

scatter = ax.scatter(xs, ys, zs, alpha=0.4, c=colors, s=ss)

ax.set_xlabel('Residual Sugar')
ax.set_ylabel('Alcohol')
ax.set_zlabel('Fixed Acidity')

# Create additional legend
UniqueColors = list(dict.fromkeys(colors))
Legend2Add = []
for color in UniqueColors:
    Legend2Add.append( Line2D([0], [0], marker='o', color='w', label=color,
           markerfacecolor=color, markersize=15, alpha=0.4) )

# Produce a legend with a cross section of sizes from the scatter
handles, labels = scatter.legend_elements(prop="sizes", alpha=0.6)
legend1 = ax.legend(handles,
                    loc="upper right", title="Classes", handles=Legend2Add, bbox_to_anchor=(1.5, 1),prop={'size': 20})
ax.add_artist(legend1)
legend2 = ax.legend(handles, labels, loc="upper right", title="Sizes", bbox_to_anchor=(1.5, 0.5), prop={'size': 20})

plt.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接