【问题标题】:How to plot 3d scatter of population density in many countries over the years?多年来,如何绘制许多国家人口密度的 3d 散点图?
【发布时间】:2019-07-25 06:11:30
【问题描述】:

我有 160 个国家的数据集,以及每个国家在 12 年内的人口密度。我想将其绘制为 3D 散点图,但出现此错误:

  • ValueError:要解压的值太多(预计 3 个)

我创建了三个列表 - “年份”、“国家名称”、“人口密度” 但似乎我做错了。 这是数据集的一个样本:

这是我的代码:

g1 = population_density["year"]
g2 = population_density["country_name"]
g3 = population_density["population_density_(people per sq. km of land area)"]

data = (g1, g2, g3)
colors= list(np.random.choice(range(256), size=160))
groups = ("year", "population density per sq.km", "countries") 

# Create plot
fig = plt.figure(figsize = (10,8))
#ax = Axes3D(fig)
ax = fig.add_subplot(111, projection='3d')
#ax = fig.gca(projection='3d')

for data, color, group in zip(data, colors, groups):
    x, y, z = data
    ax.scatter(x, y, z, alpha=0.8, c=color, edgecolors='none', s=30, label=group)

plt.title('Population Density Over The Years')
plt.legend(loc=2)
plt.show()

最后,我想要这个 3d 图的所有年份的散点图。请帮忙!

【问题讨论】:

    标签: python plot dataset mplot3d scatter3d


    【解决方案1】:

    ax.scatter(g1, g2, g3, alpha=0.8, c=color, edgecolors='none', s=30, label=group)代替ax.scatter(x, y, z, alpha=0.8, c=color, edgecolors='none', s=30, label=group)

    您应该将 x 替换为 g1,将 y 替换为 g2,将 z 替换为 g3。根据matplotlib scatter 3d 中的文档,传入的参数可以是数组形式。通过使用for 循环,您将解压缩列表中的值。

    编辑) 查看数据集后,您在 x 和 y 轴上有分类值,但是 3d 中的散点图需要您定义笛卡尔坐标。 因此,您可以做的是设置xticksyticks

    你可以通过这段代码做到这一点

    import matplotlib.pyplot as plt
    from mpl_toolkits.mplot3d import Axes3D
    import numpy as np
    
    fig = plt.figure()
    ax = fig.add_subplot(111, projection='3d')
    
    g1 = population_density["year"]
    g2 = population_density["country_name"]
    g3 = population_density["population_density_(people per sq. km of land area)"]
    
    data = (g1, g2, g3)
    colors= list(np.random.choice(range(256), size=len(g1)))
    
    ax.scatter(g1, range(len(g2)), g3, alpha=0.8, c=colors, edgecolors='none', s=30)
    
    ax.set(xticks=range(len(g1)), xticklabels=g1,
           yticks=range(len(g2)), yticklabels=g2,
           zticks=range(len(g3)), zticklabels=g3)
    
    ax.set_xlabel('year')
    ax.set_ylabel('countries')
    ax.set_zlabel('population density per sq.km')
    
    plt.title('Population Density Over The Years')
    plt.legend(loc=2)
    plt.show()
    

    【讨论】:

    • 我现在遇到了新错误:IndexError: tuple index out of range: python for color, group in zip(colors, groups): ax.scatter(g1, g2, g3, alpha=0.8, c=color, edgecolors='none', s=30, label=group)
    • @Yana 请试用代码,我已经更新了我的答案,如果您还有问题,请询问
    • 这会很困难 :) 我现在遇到了新错误:ValueError: could not convert string to float: 'Afghanistan' 难道我没有正确设置轴列表?
    • @Yana 您可能必须包含一个简短的数据集 sn-p 以让我们知道我们正在处理什么。
    • @Yana 您正在传递分类值(非整数值),因此您可以通过使用 xticksyticks 在国家的轴上相应地标记来解决这个问题。
    猜你喜欢
    • 2020-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-01-09
    • 2019-02-26
    • 1970-01-01
    • 2014-07-10
    • 2021-05-16
    • 2021-04-07
    相关资源
    最近更新 更多