Plotting list of lists in a same graph in Python - python

I am trying to plot (x,y) where as y = [[1,2,3],[4,5,6],[7,8,9]].
Say, len(x) = len(y[1]) = len(y[2])..
The length of the y is decided by the User input. I want to plot multiple plots of y in the same graph i.e, (x, y[1],y[2],y[3],...). When I tried using loop it says dimension error.
I also tried: plt.plot(x,y[i] for i in range(1,len(y)))
How do I plot ? Please help.
for i in range(1,len(y)):
plt.plot(x,y[i],label = 'id %s'%i)
plt.legend()
plt.show()

Assuming some sample values for x, below is the code that could give you the desired output.
import matplotlib.pyplot as plt
x = [1,2,3]
y = [[1,2,3],[4,5,6],[7,8,9]]
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.title("A test graph")
for i in range(len(y[0])):
plt.plot(x,[pt[i] for pt in y],label = 'id %s'%i)
plt.legend()
plt.show()
Assumptions: x and any element in y are of the same length.
The idea is reading element by element so as to construct the list (x,y[0]'s), (x,y[1]'s) and (x,y[n]'s.
Edited: Adapt the code if y contains more lists.
Below is the plot I get for this case:

Use a for loop to generate the plots and use the .show() method after the for loop.
import matplotlib.pyplot as plt
for impacts in impactData:
timefilteredForce = plt.plot(impacts)
timefilteredForce = plt.xlabel('points')
timefilteredForce = plt.ylabel('Force')
plt.show()
impactData is a list of lists.

Related

How to annotate figure by a list of strings and a list of coordinates

I am plotting a certain list, Z[i, j] of length D, using matplotlib along with the annotation of the points taken from another list, index_word_map[i], as follows:
plt.scatter(Z[:,0], Z[:,1])
for i in range(D):
plt.annotate(s=index_word_map[i], xy=(Z[i,0], Z[i,1]))
plt.show()
Now, I want to do the same using plotly or plotly express. I can plot the points using plotly express as follows:
X = []
Y = []
for i in range(D):
x = Z[i,0]
y = Z[i,1]
X.append(x)
Y.append(y)
fig = px.scatter(x=X, y=Y)
But, how am I to use the annotation list (index_word_map[i]) to have the labels of the points to show up on the plot also?
If I understand correctly, you'd like to achieve something like this:
What you're looking at here is a list D of some plotly color themes used as annotations for a scatter plot of x and y values organized as a list of lists Z.
D=['Alphabet','Antique','Bold','D3','Dark2','Dark24','G10','Light24','Pastel','Pastel1']
Z=[[0, 0],[1, 2],[2, 4],[3, 6],[4, 8],[5, 10],[6, 12],[7, 14],[8, 16],[9, 18]]
Complete code:
import numpy as np
import plotly.express as px
import plotly.graph_objs as go
# sample data
D=['Alphabet','Antique','Bold','D3','Dark2','Dark24','G10','Light24','Pastel','Pastel1']
# sample of two lists
z1 =np.arange(len(D)).tolist()
z2 = [i*2 for i in z1]
# turn two lists into a list of tuples
# containing each element of z1 of z2
# as zipped pairs
tuplist = list(zip(z1, z2))
# turn the list of tuples into list of lists
Z=[list(elem) for elem in tuplist]
# plotly setup
fig = go.Figure(data=go.Scatter(x=z1, y=z2, marker_color='black'))
for i, m in enumerate(D):
fig.add_annotation(dict(font=dict(color='rgba(0,0,200,0.8)',size=12),
x=Z[i][0],
y=Z[i][1],
showarrow=False,
text=D[i],
textangle=0,
xanchor='left',
xref="x",
yref="y"))
fig.show()
I hope this is what you were looking for. Don't hesitate to let me know if not!

Trend graph with Matplotlib

I have the following lists:
input = ['"25', '"500', '"10000', '"200000', '"1000000']
inComp = ['0.000001', '0.0110633', '4.1396405', '2569.270532', '49085.86398']
quickrComp=['0.0000001', '0.0003665', '0.005637', '0.1209121', '0.807273']
quickComp = ['0.000001', '0.0010253', '0.0318653', '0.8851902', '5.554448']
mergeComp = ['0.000224', '0.004089', '0.079448', '1.973014', '13.034443']
I need to create a trend graph to demonstrate the growth of the values of inComp, quickrComp, quickComp, mergeComp as the input values grow (input is the x-axis). I am using matplotlib.pyplot, and the following code:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(input,quickrComp, label="QR")
ax.plot(input,mergeComp, label="merge")
ax.plot(input, quickComp, label="Quick")
ax.plot(input, inComp, label="Insrção")
ax.legend()
plt.show()
However, what is happening is this: the values of the y-axis are disordered; the values of quickrComp on the y-axis are first inserted; then all mergeComp values and so on. I need the y-axis values to start at 0 and end at the highest of the 4-row values. How can I do this?
Two things: First, your y-values are strings. You need to convert the data to numeric (float) type. Second, your y-values in one of the lists are huge as compared to the remaining three lists. So you will have to convert the y-scale to logarithmic to see the trend. You can, in principle, convert your x-values to float (integers) as well but in your example, you don't need it. In case you want to do that, you will also have to remove the " from the front of each x-value.
A word of caution: Don't name your variables the same as in-built functions. In your case, you should rename input to something else, input1 for instance.
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
input1 = ['"25', '"500', '"10000', '"200000', '"1000000']
inComp = ['0.000001', '0.0110633', '4.1396405', '2569.270532', '49085.86398']
quickrComp=['0.0000001', '0.0003665', '0.005637', '0.1209121', '0.807273']
quickComp = ['0.000001', '0.0010253', '0.0318653', '0.8851902', '5.554448']
mergeComp = ['0.000224', '0.004089', '0.079448', '1.973014', '13.034443']
ax.plot(input1, list(map(float, quickrComp)), label="QR")
ax.plot(input1, list(map(float, mergeComp)), label="merge")
ax.plot(input1, list(map(float, quickComp)), label="Quick")
ax.plot(input1, list(map(float, inComp)), label="Insrção")
ax.set_yscale('log')
ax.legend()
plt.show()

How can i display data with multi markers, multi colors in matplotlib

I am a newbie in matplotlib and today i want to ask for my current problem.
Please see my code:
x = [1,2,3,4,5,6,7,8,9,10]
y = [1,2,3,4,5,6,7,8,9,10]
colors = [0,1,1,0,1,4,1,3,2,4]
sizes = [500,500,300,300,300,500,500,300,300,300]
map1 = plt.cm.get_cmap("jet", 5)
plt.scatter(x[0:3], y[0:3], c=colors[0:3] ,s=sizes[0:3],marker="*",cmap=map1)
plt.scatter(x[3:6], y[3:6], c=colors[3:6] ,s=sizes[3:6],marker="<",cmap=map1)
plt.scatter(x[6:10], y[6:10], c=colors[6:10], s=sizes[6:10],marker="D",cmap=map1)
plt.colorbar(ticks=range(5))
plt.clim(-0.5, 4.5)
plt.show()
Result Image
The problem is that i can not get the result with multiple of markers and multiple of colors. As you can see, i have a test dataset with 10 items, and i want to show 1st -> 3rd item with marker *, and the color is compatible with the colors array(1st item will be 0 color, 2nd item will be 1 color)...
Like the result image, only color of the last of plt.scatter will be true.
I dont understand where I am wrong.
Please give me some solutions.
Thank you very much
You would need to use the same color normalization for all scatter plots. This normalization would need to span over the complete range of possible color values. Otherwise the first scatter doesn't know about the second scatter's range etc.
import matplotlib.pyplot as plt
x = [1,2,3,4,5,6,7,8,9,10]
y = [1,2,3,4,5,6,7,8,9,10]
colors = [0,1,1,0,1,4,1,3,2,4]
sizes = [500,500,300,300,300,500,500,300,300,300]
map1 = plt.cm.get_cmap("jet", 5)
norm = plt.Normalize(min(colors),max(colors))
kw = dict(cmap=map1, norm=norm)
plt.scatter(x[0:3], y[0:3], c=colors[0:3] ,s=sizes[0:3],marker="*",**kw)
plt.scatter(x[3:6], y[3:6], c=colors[3:6] ,s=sizes[3:6],marker="<",**kw)
plt.scatter(x[6:10], y[6:10], c=colors[6:10], s=sizes[6:10],marker="D",**kw)
plt.colorbar(ticks=range(5))
plt.clim(-0.5, 4.5)
plt.show()

How do I use strings in matplot? [duplicate]

I am using matplotlib for a graphing application. I am trying to create a graph which has strings as the X values. However, the using plot function expects a numeric value for X.
How can I use string X values?
From matplotlib 2.1 on you can use strings in plotting functions.
import matplotlib.pyplot as plt
x = ["Apple", "Banana", "Cherry"]
y = [5,2,3]
plt.plot(x, y)
plt.show()
Note that in order to preserve the order of the input strings on the plot you need to use matplotlib >=2.2.
You should try xticks
import pylab
names = ['anne','barbara','cathy']
counts = [3230,2002,5456]
pylab.figure(1)
x = range(3)
pylab.xticks(x, names)
pylab.plot(x,counts,"g")
pylab.show()
Why not just make the x value some auto-incrementing number and then change the label?
--jed
Here's one way which i know works, though i would think creating custom symbols is a more natural way accomplish this.
from matplotlib import pyplot as PLT
# make up some data for this example
t = range(8)
s = 7 * t + 5
# make up some data labels which we want to appear in place of the symbols
x = 8 * "dp".split()
y = map(str, range(8))
data_labels = [ i+j for i, j in zip(x, y)]
fig = PLT.figure()
ax1 = fig.add_subplot(111)
ax1.plot(t, s, "o", mfc="#FFFFFF") # set the symbol color so they are invisible
for a, b, c in zip(t, s, data_labels) :
ax1.text(a, b, c, color="green")
PLT.show()
So this puts "dp1", "dp2",... in place of each of the original data symbols--in essence creating custom "text symbols" though again i have to believe there's a more direct way to do this in matplotlib (without using Artists).
I couldn't find a convenient way to accomplish that, so I resorted to this little helper function.
import matplotlib.pyplot as p
def plot_classes(x, y, plotfun=p.scatter, **kwargs):
from itertools import count
import numpy as np
classes = sorted(set(x))
class_dict = dict(zip(classes, count()))
class_map = lambda x: class_dict[x]
plotfun(map(class_map, x), y, **kwargs)
p.xticks(np.arange(len(classes)), classes)
Then, calling plot_classes(data["class"], data["y"], marker="+") should work as expected.

Python - Graphing contents of mutliple files

I have lists of ~10 corresponding input files containing columns of tab separated data approx 300 lines/datapoints each.
I'm looking to plot the contents of each set of data such that I have a 2 plots for each set of data one is simply of x vs (y1,y2,y3,...) and one which is transformed by a function e.g. x vs (f(y1), f(y2),f(y3),...).
I am not sure of the best way to achieve it, I thought about using a simple array of filenames then couldn't work out how to store them all without overwriting the data - something like this:
import numpy as np
import matplotlib.pyplot as plt
def ReadDataFile(file):
print (file)
x,y = np.loadtxt(file, unpack=True, usecols=(8,9))
return x, y
inputFiles = ['data1.txt','data2.txt','data2.txt',...]
for file in inputFiles:
x1,y1 = ReadDataFile(file) ## ? ##
p1,q1 = function(x1,y1) ## ? ##
plt.figure(1)
plt.plot(x1,y1)
plt.plot(x2,y2)
...
# plt.savefig(...)
plt.figure(2)
plt.plot(p1,q1)
plt.plot(p2,q2)
...
# plt.savefig(...)
plt.show()
I guess my question is how to best read and store all the data and maintain tha ability to access it without needing to put all the code in the readloop. Can I read two data sets into a list of pairs? Is that a thing in Python? if so, how do I access them?
Thanks in advance for any help!
Best regards!
Basically, I think you should put all your code in the readloop, because that will work easily. There's a slightly different way of using matplotlib that makes it easy to use the existing organization of your data AND write shorter code. Here's a toy, but complete, example:
import matplotlib.pyplot as plt
from numpy.random import random
fig, axs = plt.subplots(2)
for c in 'abc': # In your case, for filename in [file-list]:
x, y = random((2, 5))
axs[0].plot(x, y, label=c) # filename instead of c in your case
axs[1].plot(x, y**2, label=c) # Plot p(x,y), q(x,y) in your case
axs[0].legend() # handy to get this from the data list
fig.savefig('two_plots.png')
You can also create two figures and plot into each of them explicitly, if you need them in different files for page layout, etc:
import matplotlib.pyplot as plt
from numpy.random import random
fig1, ax1 = plt.subplots(1)
fig2, ax2 = plt.subplots(1)
for c in 'abc': # or, for filename in [file-list]:
x, y = random((2, 5))
ax1.plot(x, y, label=c)
ax2.plot(x, y**2, label=c)
ax1.legend()
ax2.legend()
fig1.savefig('two_plots_1.png')
fig2.savefig('two_plots_2.png')

Categories

Resources