【问题标题】:Matplotlib Legend doesn't show up in 3D-scatterplotMatplotlib Legend 未出现在 3D 散点图中
【发布时间】:2023-03-05 14:50:01
【问题描述】:

我正在尝试使用 matplotlib 绘制 3D 散点图,但由于某种原因,输出没有显示在图例中。 我希望图例成为我的数据框列(类别)之一。

fig = plt.figure(figsize=(12,8))
ax = Axes3D(fig)

color_dict = { 'Beauty':'red', 'Kids':'green', 'Food':'blue', 'Jewelry':'yellow')}

names = df['category'].unique()

for s in names:
  sc = ax.scatter(embedding[:,0], embedding[:,1], embedding[:,2], s=40,
  color=[color_dict[i] for i in df_brands['category']], marker='x', label=names[s])

ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')
ax.set_zlabel('Z Label')
ax.legend()
# plt.show()
plt.legend(*sc.legend_elements(), bbox_to_anchor=(1.05, 1), loc=2)

从下面的输出中可以看出,图例显示在右上角,所有类别的颜色都相同(红色)。 (我将代码简化为 4 种颜色,忽略情节中有更多颜色的事实)。

任何帮助将不胜感激。 谢谢!

【问题讨论】:

    标签: python pandas matplotlib scatter-plot scatter3d


    【解决方案1】:

    在散点图的情况下,图例信息不会自动汇总,所以是循环设置的。仅针对测试数据,我们已按情节实施。

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    import pandas as pd
    
    import plotly.express as px
    df = px.data.iris()
    fig = plt.figure(figsize=(12,8))
    
    ax = fig.add_subplot(111, projection='3d')
    
    color_dict = {'setosa':'red', 'versicolor':'green', 'virginica':'blue'}
    
    names = df['species'].unique()
    
    for s in names:
        embedding = df.loc[df['species'] == s]
        sc = ax.scatter(embedding.iloc[:,0], embedding.iloc[:,1], embedding.iloc[:,2], s=40,
        c=[color_dict[i] for i in embedding['species']], marker='x',  label=s)
        plt.legend(loc=2, bbox_to_anchor=(1.05, 1))
        
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    
    plt.show()
    

    【讨论】:

    • 请您查看相关question。提前致谢
    【解决方案2】:

    您需要以列表的形式向ax.legend() 函数调用添加参数,告诉它您需要显示什么图例。

    添加loc="upper right" 参数以将图例定位到右上角。

    类似这样的:

    # importing modules
    import numpy as np
    import matplotlib.pyplot as plt
    
    # Y-axis values
    y1 = [2, 3, 4.5]
    
    # Y-axis values
    y2 = [1, 1.5, 5]
    
    # Function to plot
    plt.plot(y1)
    plt.plot(y2)
    
    # Function add a legend
    plt.legend(["blue", "green"], loc ="upper right")
    
    # function to show the plot
    plt.show()
    

    输出: Output1

    另外,请参阅此页面以供参考: https://www.geeksforgeeks.org/matplotlib-pyplot-legend-in-python/

    所以,我会将您的图例问题解决为:

    fig = plt.figure(figsize=(12,8))
    ax = Axes3D(fig)
    
    color_dict = { 'Beauty':'red', 'Kids':'green', 'Food':'blue', 'Jewelry':'yellow')}
    
    names = df['category'].unique()
    
    sc = ax.scatter(embedding[:,0], embedding[:,1], embedding[:,2], s=40,
    color=[color_dict[i] for i in df_brands['category']], marker='x', label=names)
    
    ax.set_xlabel('X Label')
    ax.set_ylabel('Y Label')
    ax.set_zlabel('Z Label')
    ax.legend(['Label1', 'Label2', 'Label3', 'Label4') # 4 Labels for 4 colours
    # plt.show()
    plt.legend(*sc.legend_elements(), bbox_to_anchor=(1.05, 1), loc=2)
    

    我无法显示您改进后的代码的输出,因为我没有您的数据框

    【讨论】:

    • 这仅在图中添加了第一个标签(在本例中为Beauty
    • 您是否以列表的形式添加了 3 个图例作为参数?还是只有 1 个?也发送所做的。
    • 是的,我确实添加了您在上面发布的列表,在 loc ="upper right" 旁边。我设法使用 for 循环显示图例。但现在的问题是图例显示所有数据点都是红色的(绘图显示多种颜色)。我将编辑我的问题,以便您查看我的最新代码。
    猜你喜欢
    • 1970-01-01
    • 2012-07-07
    • 2015-10-18
    • 2012-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-31
    相关资源
    最近更新 更多