Python Plot of Array Produces Two Lines Instead of One - python

Plotted an array generated from comma separated files and it plotted two lines instead of the correct one (orange). If any one has could offer a solution or any suggestions it would be greatly appreciated!
import numpy as np
import matplotlib.pyplot as plt
file = open("com.txt","r")
X, Y = [], []
npy_array = np.loadtxt(file, delimiter=",")
plt.plot(npy_array)
plt.show()
enter image description here

It seems that you have loaded tabulated data into a 2d array. You need to separate this into independent and dependent variables and then plot one against the other, rather than plot both lines against the array index. (Clearly the linearly increasing data in your blue line is intended to be the independent variable, and should be your "x" values, ranging from 0 to approximately 0.2.) Assuming that the lines of the file are in the order x,y, you would do this -- otherwise swap the 0 and 1.
# to start with, some lines unchanged from the question
import numpy as np
import matplotlib.pyplot as plt
file = open("com.txt","r")
npy_array = np.loadtxt(file, delimiter=",")
# below here: what you need to change
x = npy_array[:,0]
y = npy_array[:,1]
plt.plot(x, y)

matplotlib plots 2d numpy arrays assuming each column is a different set of data, and should each be plotted indigently
a = [[0,1,2,3], [0,2,3,6]]
np_a = np.array(a)
plt.plot(np_a,'x:')
plt.show()
because the line is a strait one, I assume you want that to be your x axis. To do that you have to pass the x axis as the first perimeter, and the y axis as the second
a = [[0,1,2,3], [0,2,3,6]]
np_a = np.array(a)
plt.plot(np_a[0],np_a[1],'x:')
plt.show()

Related

How to reduce thickness of a line when width does not work?

import matplotlib.pyplot as plt
import numpy as np
import csv as csv
x=[]
y=[]
with open('DTS_02.csv', 'r') as csvfile:
plots=csv.reader(csvfile, delimiter=';')
for row in plots:
x.append(float(row[1]))
y.append(float(row[2]))
plt.plot(x,y, label='Hello,World')
plt.xlabel('depth')
plt.ylabel('temperature')
plt.grid()
plt.title('1-e6')
plt.show()
picture --> [1]: https://i.stack.imgur.com/9T4lP.png
So I am trying to execute this one and my sample contains 1 million rows. There are two 2 problems
1.Why do I get such a thick line?
2.Why there is a line connecting starting and end point?
Additionally, what would be your advice on improving this code(Without shifting to a new module)...
A1: because you are plotting a line, and I suspect x is not sorted.
A2. See question 1.
A3: use the following and see how it works (since you are using numpy):
x = np.array(x)
y = np.array(y)
plt.plot(x[x.argsort()], y[x.argsort()], label='Hello,World')
EDIT:
If you are having a lot of noise, you can try plotting less points, e.g.:
plt.plot(x[x.argsort()][::3], y[x.argsort()][::3], label='Hello,World') #each 3 points
Or plot a moving average (see here)

Plot matrix of weighted cells in grid with Matplotlib

I have a square matrix built from an array of random integers, defined below:
import numpy as np
dim_low, dim_high = 0, 20 #array of random integers' dimensions
matrix = np.random.random_integers(low = dim_low,high = dim_high, size=(dim_high,dim_high))
print(matrix) #the matrix of defined with repetitions of the array.
Resulted matrix in the picture:
https://i.stack.imgur.com/eEcCh.png
What could I do to plot the matrix generated in a grid with Matplotlib, in a way that the values of each cell (the weights) are printed in the center of each cell, and there's a scale from 0 to 20 in x an y axis, as in the picture below (notice that 'x' and 'o' are text in the example, what I need is the weights, in integer form, not text form):
https://i.stack.imgur.com/9mBuG.png (here)
I pulled most of this from this post.
import numpy as np
import matplotlib.pyplot as plt
low_dim = 0
high_dim = 20
matrix = np.random.randint(low_dim, high_dim, (high_dim,high_dim))
fig, ax = plt.subplots()
for i in range(0, high_dim):
for j in range(0, high_dim):
val = matrix[i,j]
ax.text(i+0.5, j+0.5, str(val), va='center', ha='center')
ax.set_xlim(low_dim, high_dim)
ax.set_ylim(low_dim, high_dim)
ax.set_xticks(np.arange(high_dim))
ax.set_yticks(np.arange(high_dim))
ax.grid()
plt.show()
The right module for this would be seaborn. It has all the functionality you ask for and more...
Try using https://seaborn.pydata.org/generated/seaborn.heatmap.html. I won't take you through the different options because they're really well documented.
Goodluck!
BTW, you'll want to use a panda pivot table for comfortable compatibility.

Summing lines in pyplot

I have a pyplot figure with a few lines on it. I would like to be able to draw an extra line, which would be a sum of all others' values. The lines are not plotted against the same x values (they are visually shorter in the plot - see the image). The resulting line would be somewhat above all others.
One idea I have for it requires obtaining a line's y value in a specific x point. Is there such a function? Or does pyplot/matplotlib support summing lines' values?
Superposition it the short answer to your question: read this for more.
Example:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(100) #range of x axis
y1 = np.random.rand(100,1) #some random numbers
y2 = np.random.rand(100,1)
#this will only plot y1 value
plt.plot(x,y1)
plt.show()
#this will plot summation of two elements
plt.plot(x,y1+y2)
plt.show()
I took a second look at your question, what I saw is your y values have different length so adding them would not be the case as shown in example above. What you can do is create equal sized 4 lists, where non existing values in that list is zero, then you can apply super position to this (simply add all of them and then plot)
For the future generations: numpy.interp() was my solution to this problem.

Having line color vary with data index for line graph in matplotlib?

So I have a 2D array of data producing a plot of many timeseries on the same axes. At the moment, the colour of each line just cycles through and doesn't mean anything.
I want to somehow map the colour of each line to the index of its data - so a set of data with a low index appears red and then fades to blue at a high index.
To clarify, each individual line should be the same colour throughout, not fading with time. The difference should be between each line.
Thankyou!
Often you pass a colormap to a plotting function, but you can also pass a number or array to a colormap and get the colors in return.
So to color each line according to a variable, do something like this:
numlines = 20
for i in np.linspace(0,1, numlines):
plt.plot(np.arange(numlines),np.tile([i],numlines), linewidth=4, color=plt.cm.RdYlBu(i))
plot(x,y,'r') for red lines
plot(x,y,'b') for blue lines
Need more colors for a decent X'mas? See here.
UPDATES:
As you asked, there're too many lines to manually set colors. So how about this:
from matplotlib.pyplot import *
x = list(range(10))
amount = 20
for i in range(amount):
y = [j-i for j in x]
c = [float(i)/float(amount), 0.0, float(amount-i)/float(amount)] #R,G,B
plot(x, y, color=c)
show()
It gives:
if someone is still looking for a way to color the curve along the path using some colormap, without using a scatter, I think the better way is to split it to segments and call colormap for the color
import matplotlib.pyplot as plt
import numpy as np
def plot_colored(x, y, c, cmap=plt.cm.jet, steps=10):
c = np.asarray(c)
c -= c.min()
c /= c.max()
it=0
while it<с.size-steps:
x_segm = x[it:it+steps+1]
y_segm = y[it:it+steps+1]
c_segm = cmap( c[it+steps//2] )
plt.plot(x_segm, y_segm, c=c_segm)
it += steps
# sample track
t = np.r_[0:10:1000j]
x = t**.25*np.sin(2*np.pi*t)
y = t**.25*np.cos(2*np.pi*t)
plt.figure()
plot_colored(x, y, t)
(smaller step makes it smoother but slower)
Here I use rgb colors to get an array of 200 different colors. I don't have the time to sort them by intensity, but do a few printouts of the array and you might figure out how. An idea is to sort by the index of the sum of the (sorted) tuples.
#colorwheel
import matplotlib.pyplot as plt
from itertools import permutations
from random import sample
import numpy as np
#Get the color-wheel
Nlines = 200
color_lvl = 8
rgb = np.array(list(permutations(range(0,256,color_lvl),3)))/255.0
colors = sample(rgb,Nlines)
#Plots
x = np.linspace(0,2*np.pi)
for i in range(Nlines):
plt.plot(i*np.cos(x),i*np.sin(x),color=colors[i]) #color from index
plt.savefig("SO_colorwheel.png")
plt.show()
Gives

Merge two existing plots into one plot

I haven't really attempted any way to do this, but I am wondering if there is a way to merge two plots that already exist into one graph. Any input would be greatly appreciated!
Here is a complete minimal working example that goes through all the steps you need to extract and combine the data from multiple plots.
import numpy as np
import pylab as plt
# Create some test data
secret_data_X1 = np.linspace(0,1,100)
secret_data_Y1 = secret_data_X1**2
secret_data_X2 = np.linspace(1,2,100)
secret_data_Y2 = secret_data_X2**2
# Show the secret data
plt.subplot(2,1,1)
plt.plot(secret_data_X1,secret_data_Y1,'r')
plt.plot(secret_data_X2,secret_data_Y2,'b')
# Loop through the plots created and find the x,y values
X,Y = [], []
for lines in plt.gca().get_lines():
for x,y in lines.get_xydata():
X.append(x)
Y.append(y)
# If you are doing a line plot, we don't know if the x values are
# sequential, we sort based off the x-values
idx = np.argsort(X)
X = np.array(X)[idx]
Y = np.array(Y)[idx]
plt.subplot(2,1,2)
plt.plot(X,Y,'g')
plt.show()
Assuming you are using Matplotlib, you can get the data for a figure as an NX2 numpy array like so:
gca().get_lines()[n].get_xydata()

Categories