2

I would like to plot select data from a dictionary of the following format:

dictdata = {key_A: [(1,2),(1,3)]; key_B: [(3,2),(2,3)]; key_C: [(4,2),(1,4)]}

I am using the following function to extract data corresponding to a specific key and then separate the x and y values into two lists which can be plotted.

def plot_dictdata(ax1, key):
    data = list()
    data.append(dictdata[key])
    for list_of_points in data:
        for point in list_of_points:
            x = point[0]
            y = point[1]
    ax1.scatter(x,y)

I'd like to be able to call this function multiple times (see code below) and have all relevant sets of data appear on the same graph. However, the final plot only shows the last set of data. How can I graph all sets of data on the same graph without clearing the previous set of data?

fig, ax1 = plt.subplots()
plot_dictdata(ax1, "key_A") 
plot_dictdata(ax1, "key_B") 
plot_dictdata(ax1, "key_C")
plt.show()

I have only just started using matplotlib, and wasn't able to figure out a solution using the following examples discussing related problems. Thank you in advance. how to add a plot on top of another plot in matplotlib? How to draw multiple line graph by using matplotlib in Python Plotting a continuous stream of data with MatPlotLib

1 Answers1

1

It could be that the problem is at a different point than you think it to be. The reason you only get the last point plotted is that in each loop step x and y are getting reassigned, such that at the end of the loop, each of them contain a single value.

As a solution you might want to use a list to append the values to, like

import matplotlib.pyplot as plt

dictdata = {"key_A": [(1,2),(1,3)], "key_B": [(3,2),(2,3)], "key_C": [(4,2),(1,4)]}

def plot_dictdata(ax1, key):
    data = list()
    data.append(dictdata[key])
    x=[];y=[]
    for list_of_points in data:
        for point in list_of_points:
            x.append(point[0])
            y.append(point[1])
    ax1.scatter(x,y)

fig, ax1 = plt.subplots()
plot_dictdata(ax1, "key_A") 
plot_dictdata(ax1, "key_B") 
plot_dictdata(ax1, "key_C")
plt.show()

resulting in
enter image description here

It would be worth noting that the plot_dictdata function could be simplified a lot, giving the same result as the above:

def plot_dictdata(ax1, key):
    x,y = zip(*dictdata[key])
    ax1.scatter(x,y)
ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • You were right in your assumption that the error was not where I had expected. The simplification was also useful as I had not yet encountered the zip function. Thank you! – slithytovesNborogroves Sep 08 '17 at 02:48