I am new to Python and I need to generate a graph using pyplot and matplotlib like the one in the attached picture. So far I tried it like this:
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,1,2,3])
y = np.array([20,21,22,23])
my_xticks = ['John','Arnold','Mavis','Matt']
plt.xticks(x, my_xticks)
plt.plot(x, y)
plt.show()
But my problem is how can I specify a different number of values on the y axis different from the number of values on the x axis? And maybe specify them as an interval with 0.005 difference instead of a list? Many thanks!
import matplotlib.pyplot as plt
import numpy as np
x = np.array([0,1,2,3])
y = np.array([0.650, 0.660, 0.675, 0.685])
my_xticks = ['a', 'b', 'c', 'd']
plt.xticks(x, my_xticks)
plt.yticks(np.arange(y.min(), y.max(), 0.005))
plt.plot(x, y)
plt.grid(axis='y', linestyle='-')
plt.show()
Something like this should work.
Related
This is a simplified example of a problem I am having.
import matplotlib.pyplot as plt
for i in range(0,10):
plt.plot(i, i + 1)
plt.show()
shows this. and
x = y = []
for i in range(0,10):
x.append(i)
y.append(i + 1)
plt.plot(x, y,)
plt.show()
shows this.
How can I plot points in a loop so that I don't need to create two arrays?
Try this-
import matplotlib.pyplot as plt
for i in range(0,10):
plt.plot(i, i + 1, color='green', linestyle='solid', linewidth = 3,
marker='o')
plt.show()
Pass array as the first argumet to plt.plot(), this would plot y using x as index array 0..N-1:
import matplotlib.pyplot as plt
# plot y using x as index array 0..N-1
plt.plot(range(10))
plt.show()
You'll find more interesting information at plt.plot().
You can do it with:
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
fig, ax = plt.subplots()
max =10
for i in range(0,max):
#scatter:
#s=0 to make dissapeared the scatters
ax.scatter(i, i + 1,s=1,facecolor='blue')
#lines
if i > 0:
lc = LineCollection([[(i-1, i),(i, i+1)]])
ax.add_collection(lc)
plt.show()
result:
import numpy as np
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1))
plt.show()
shows
But if I set unit to 0.5:
plt.xticks(np.arange(min(x), max(x)+1, 0.5)) shows
x-axis is hardly readable.
Is there a way to set distance for every x-axis unit so it could extend the plot automatically (on x direction)?
This works:
import numpy as np
import matplotlib.pyplot as plt
x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.figure(figsize=(20,10))
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 0.5))
plt.show()
Operating on size of the figure does the job. Play with it, find your desired size/ratio etc.
I have a file 'mydata.tmp' which contains 3 colums like this:
3.81107 0.624698 0.000331622
3.86505 0.624698 0.000131237
3.91903 0.624698 5.15136e-05
3.97301 0.624698 1.93627e-05
1.32802 0.874721 1.59245
1.382 0.874721 0
1.43598 0.874721 0
1.48996 0.874721 4.27933
etc.
Then I want to make a heatmap color plot where the first two columns are coordinates, and the third column are the values of that coordinates.
Also, I would like to set the third column in log scale.
How can I do this?
I have tried the following code using a scatter type of plot
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
df = pd.read_csv('mydata.tmp', delim_whitespace=True,
comment='#',header=None,
names=['a','b','c'])
fig, ax = plt.subplots()
sc = ax.scatter(df.a, df.b, c=df.c, cmap="GnBu", s=400,
norm=matplotlib.colors.LogNorm())
fig.colorbar(sc, ax=ax)
plt.show()
and I get the picture I show below (Ignore the scale of the x axis). However I want to get the result I achieve when I do it whit GNUplot with this code (I also attach the GNUplot Image)
plot mydata.tmp using 1:2:3 with image
Maybe I have to use pcolormesh?
Thank you!
GNUplot Image:
Matplotlib Image:
When I try Khalil code I get this Image:
Try this. Tested and working on some data I have.
Spacing is very important. set it according the gridding you want for the plot. The higher the spacing the smoother THE image is but longer calculation.
import pandas as pd
import matplotlib.pyplot as plt
import scipy.interpolate
import numpy as np
import matplotlib.colors as colors
# import data
df = pd.read_csv('mydata.tmp', delim_whitespace=True,
comment='#',header=None,
names=['1','2','3'])
x = df['1']
y = df['2']
z = df['3']
# Set up a regular grid of interpolation points
spacing = 500
xi, yi = np.linspace(x.min(), x.max(), spacing), np.linspace(y.min(),
y.max(), spacing)
XI, YI = np.meshgrid(xi, yi)
# Interpolate
rbf = scipy.interpolate.Rbf(x, y, z, function='linear')
ZI = rbf(XI, YI)
#plot
fig, ax = plt.subplots()
sc = ax.imshow(ZI, vmin=z.min(), vmax=z.max(), origin='lower',
extent=[x.min(), x.max(), y.min(),
y.max()], cmap="GnBu", norm=colors.LogNorm(vmin=ZI.min(),
vmax=ZI.max()))
fig.colorbar(sc, ax=ax, fraction=0.05, pad=0.01)
plt.show()
The following code will create a plot by connecting points.
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.plot(x, y)
plt.show()
How can I change the plot to vertical sticks instead of connecting points? I.e., change to the type of plot of the following example:
Thanks.
Use plt.bar
import numpy as np
import matplotlib.pyplot as plt
x = np.arange(0, 5, 0.1);
y = np.sin(x)
plt.bar(x, y, width=0.08,edgecolor='None',color='k',align='center')
plt.show()
I assume this is a simple fix. I'm trying to replace integer values in a 3d bar chart in matplotlib with string names, and the last one inexplicably won't show:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
fig = plt.figure(figsize=(11,8.5))
ax = fig.add_subplot(111, projection='3d')
for c, z in zip([qwer for qwer in ['r', 'g', 'b', 'y']*20][:len(sss.keys())], sss.keys()):
xs = np.array(sss[z].keys())
ys = np.array([sss[z][key] for key in sss[z]])
cs = [c] * len(xs)
ax.bar(xs, ys, zs=z, zdir='y', color=cs, alpha=0.8)
ax.set_xlabel('Second Interval')
ax.set_ylabel('First Interval')
ax.set_zlabel('Frequency')
ax.set_xticklabels(['skip down','step down','stay','step up','skip up'])
ax.set_yticklabels(['','skip down','','step down','','stay','','step up','','skip up'])
ax.set_title('Proportional Frequency of S/S/S Intervals by Previous Interval')
plt.show()
sss is a dictionary with other dictionaries as values.
Unfortunately I can't post images, but essentially the chart looks all good and all the string labels on the x and y axes work except 'skip up' along the y axis. It's right at the corner between the y and z axes and just doesn't appear.
What's up?