gpt4 book ai didi

python - 在字典中绘制嵌套列表 - python

转载 作者:太空宇宙 更新时间:2023-11-04 02:24:09 25 4
gpt4 key购买 nike

我的数据集看起来像这样:

{'Berlin': [[1, 333]],
'London': [[1, 111], [2, 555]],
'Paris': [[1, 444], [2, 222], [3, 999]]}

现在我需要为每个城市绘制散点图,例如,巴黎的散点图在 x 轴上的数字应为:1 2 3,在 y 轴上的数字应为:444 222 999。

我有一个非常大的数据集,所以我希望每个地 block 有 5 个城市。

我的代码看起来像这样,但在输出中我得到了空图。

for town in dictionary_town:
x=[]
y=[]
i+=1
save_plot = 'path'+str(i)+'.png'

for list in town:
x.append(list[0])
y.append(list[1])

plt.style.use('dark_background')
plt.figure()
plt.plot( kind='scatter',x = x, y=y,label=town, s=30,figsize=(50, 20), fontsize=25, alpha=0.5)
plt.ylabel("Population", fontsize=50)
plt.title(str(i), fontsize=50)
legend = plt.legend(fontsize=30, markerscale=0.5, ncol=1)
plt.savefig(save_plot)
plt.close()

最佳答案

这里是用于保存图表的最小工作代码。为了简单起见,我故意省略了代码中的图形样式部分。

import matplotlib.pyplot as plt

dictionary_town = {'Berlin': [[1, 333]],
'London': [[1, 111], [2, 555]],
'Paris': [[1, 444], [2, 222], [3, 999]]}

path = '/your_path_to_image_saving/' #pls change here
i = 0
for town, values in dictionary_town.items():
x = []
y = []
i += 1
save_plot = path + str(i) + '.png'
for value in values:
x.append(value[0])
y.append(value[1])
plt.figure()
plt.scatter(x=x, y=y, label=town)
plt.ylabel("Population")
plt.title(str(i))
plt.legend(loc=4)
plt.savefig(save_plot)
plt.close()

我建议你从这里开始,一个一个地添加一些样式,找出问题所在。

希望这对您有所帮助。


编辑:一次绘制 5 个城市。如果你想改变# of cities,改变chunk。此外,如果 # of cities 需要大于 5,则需要相应地添加 colors

import matplotlib.pyplot as plt
import numpy as np

dictionary_town = {'Berlin': [[1, 333]],
'London': [[1, 111], [2, 555]],
'Paris': [[1, 444], [2, 222], [3, 999]]}

colors = {1: 'r', 2: 'b', 3: 'g', 4: 'k', 5: 'grey'}

path = '/your_path_to_image_saving/' #pls change here
i = 0
chunk = 5
for town, values in dictionary_town.items():
i += 1
values = np.array(values)
x = values[:,0]
y = values[:,1]
plt.scatter(x=x, y=y, label=town, color=colors[(i+1)%chunk+1])
if i % chunk == 0:
save_plot = path + str(i) + '.png'
plt.ylabel("Population")
plt.title(str(i))
plt.legend(loc=4)
plt.savefig(save_plot)
plt.close()
elif (i == len(dictionary_town)) & (i % chunk != 0):
save_plot = path + str(i) + '.png'
plt.ylabel("Population")
plt.title(str(i))
plt.legend(loc=4)
plt.savefig(save_plot)
plt.close()

关于python - 在字典中绘制嵌套列表 - python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50886451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com