Neven
Neven

Reputation: 453

Ploting nested lists in dictionary - python

My dataset is looking something like this:

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

And for each city now I need to make scatter plot, for example, the plot of Paris should have on x-axis numbers: 1 2 3, and on the y-axis: 444 222 999.

I have a really big dataset, so I would like to have 5 cities per plot.

My code is looking something like this, but on the output I get empty plots.

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()

Upvotes: 2

Views: 965

Answers (2)

gyoza
gyoza

Reputation: 2152

Here is a minimum working piece of code just to focus on saving graphs. I intentionally omitted graph-styling parts of your code to be simple.

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()

I recommend you to start from here and add some stylings one by one to figure out what's wrong.

Hope this helps.


EDIT: Plot 5 cities at a time. If you want to change # of cities, change chunk. Also, if # of cities needs to be larger than 5, colors needs to be added accordingly.

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()

Upvotes: 2

taras
taras

Reputation: 6914

You can simply transpose your lists with zip in order to convert x, y pairs to lists:

import matplotlib.pyplot as plt

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


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

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

Upvotes: 0

Related Questions