How to make figure rectangle in Matplotlib - matplotlib

I have drawn the following figure. Is it possible to make the figure with length 2 unit & height 1 unit? Also is it possible to change plt.xlabel('time (s)') to plt.xlabel('$\alpha \rightarrow$')?
import matplotlib.pyplot as plt
import numpy as np
t=[0,1,2]
s=[0.05,0.1,0.2]
plt.plot(t, s)
plt.xlabel('time (s)')
plt.ylabel('voltage (mV)')
#plt.title('About as simple as it gets, folks')
plt.grid(True)
plt.savefig("test.png")
plt.show()

You answered your own question about the figure size.
For the second question you just need a raw string, e.g.: plt.xlabel(r'$\alpha \rightarrow$')
To make the alpha bold -- as requested in a comment -- it's a little more involved. Per https://tex.stackexchange.com/a/99286 you'd do:
import matplotlib
matplotlib.rc('text', usetex=True)
matplotlib.rcParams['text.latex.preamble']=[r"\usepackage{amsbsy}"]
t=[0,1,2]
s=[0.05,0.1,0.2]
plt.plot(t, s)
plt.ylabel('voltage (mV)')
plt.xlabel(r'$\pmb{\alpha}$ \rightarrow$')
plt.show()

Related

Scale Y axis of matplotlib plot in jupyter notebook

I want to scale Y axis so that I can see values, as code below plots cant see anything other than a thin black line. Changing plot height doesn't expand the plot.
import numpy as np
import matplotlib.pyplot as plt
data=np.random.random((4,10000))
plt.rcParams["figure.figsize"] = (20,100)
#or swap line above with one below, still no change in plot height
#fig=plt.figure(figsize=(20, 100))
plt.matshow(data)
plt.show()
One way to do this is just repeat the values then plot result, but I would have thought it possible to just scale the height of the plot?
data_repeated = np.repeat(data, repeats=1000, axis=0)
You can do it like this:
import numpy as np
import matplotlib.pyplot as plt
data=np.random.random((4, 10000))
plt.figure(figsize=(40, 10))
plt.matshow(data, fignum=1, aspect='auto')
plt.show()
Output:

plot shuffled array numpy

I am writting a very simple script, one that plot a sin using jupyter notebook (python 3). when I put:
import numpy
import matplotlib.pyplot as plt
x=np.arange(0.0,5*np.pi,0.001)
y = np.sin(x)
plt.plot(x,y)
The plot is fine.
However if :
import numpy
import matplotlib.pyplot as plt
x=np.arange(0.0,5*np.pi,0.001)
np.random.shuffle(x)
y = np.sin(x)
plt.plot(x,y)
the image is
I don't understand why shuffling the x BEFORE I ran sin does it.
thank you
Let's first simplify things a bit. We plot 4 points and annote them with the order in which they are plotted.
import numpy as np; np.random.seed(42)
import matplotlib.pyplot as plt
x=np.arange(4)
y = np.sin(x)
plt.plot(x,y, marker="o")
for i, (xi,yi) in enumerate(zip(x,y)):
plt.annotate(str(i), xy=(xi,yi), xytext=(0,4),
textcoords="offset points", ha="center")
plt.show()
No if we shuffle x and plot the same graph,
x=np.arange(4)
np.random.shuffle(x)
y = np.sin(x)
we see that positions of the points are still are the same, but while e.g. previously the first point was the one at (0,0), it's now the third one appearing there. Due to this randomized order, the connecting lines go zickzack.
Now if you use enough points, all those lines will add up to look like a complete surface, which is what you get in your image.

histogram2d heatmap manipulation

I created a heatmap from a scatterplot of csv values using the code i found from a different stackoverflow thread here Generate a heatmap in MatPlotLib using a scatter data set
This works but I'd like to edit the colours/smooth between bins etc. I've read this https://matplotlib.org/examples/color/colormaps_reference.html ...but my level of n00b is preventing swift progress. Does my current code seem ameanable to easy manipulation for interpolation between bins (smoothing) or at least a colour change, or do I need to create my heatmap in a different way to gain more control? (the heatmap will represent how often a space is used in time, based on x y values of a tracked item)
Thanks , any help much appreciated.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl
import csv
with open('myfile.csv') as csvfile:
readCSV = csv.reader(csvfile, delimiter=',')
y = []
x = []
for row in readCSV:
x.append(float(row [0]))
y.append(float(row [1]))
print (x, y)
heatmap, xedges, yedges = np.histogram2d(x,y,bins=20)
extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]]
plt.clf()
plt.imshow(heatmap.T, extent=extent)
plt.show()

Overlapping axis label with length distribution

I'm a newbie in python plot, I want to plot the lists with this code:
import numpy as np
import matplotlib.pyplot as plt
alphab = [172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,287,288,289,290,291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,309,310,311,312,313,314,315,316,317,318,319,320,321,322,323,324,325,326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,343,344,345,346,347,348,349,350,351,352,353,354,355,356,357,358,359,360,361,362,363,364,365,366,367,368,369,370,371,372,373,374,375,376,377,378,379,380,381,382,383,384,385,386,387,388,389,390,391,392,393,394,395,396,397,398,399,400,401,402,403,404,405,406,407,408,409,410,411,412,413,414,415,416,417,418,419,420,421,422,423,424,425,426,427,428,429,430,431,432,433,434,435,436,437,438,439,440,441,442,443,444,445,446,447,448,449,450,451,452,453,454,455,456,457,458,459,460,461,462,463,464,465]
frequencies = [24,17,21,27,10,21,26,41,23,27,25,22,21,24,31,24,19,18,27,15,29,28,22,35,35,28,30,20,29,42,39,35,30,29,38,32,35,47,30,44,55,34,41,41,46,56,39,39,57,39,58,44,51,52,51,44,57,48,50,59,54,46,64,63,56,60,74,72,75,72,60,75,74,55,75,69,70,69,73,69,63,80,70,74,62,77,69,78,70,68,68,80,71,77,79,64,83,76,64,92,77,93,86,65,88,86,79,91,79,97,87,67,83,96,94,79,102,114,89,92,90,112,100,107,98,95,99,95,96,91,103,111,85,105,113,103,105,95,110,103,111,102,102,117,127,128,110,100,122,99,126,99,113,114,133,129,118,120,105,121,112,115,118,127,109,116,96,101,98,98,94,114,94,87,83,117,87,105,120,116,96,112,92,106,115,107,98,107,87,86,111,108,113,106,109,102,89,81,102,87,124,127,116,106,98,106,117,95,113,107,121,92,102,97,94,94,122,110,101,118,112,106,95,112,115,102,136,114,125,136,126,120,116,119,140,114,125,148,126,137,140,129,134,124,141,126,127,124,162,124,137,136,137,142,156,131,153,150,139,131,143,119,145,142,135,151,117,143,151,146,149,125,109,124,135,144,125,127,161,120,158,112,129,125,134,131,130,122,118,145,132,123,131,129]
pos = np.arange(len(alphab))
plt.bar(pos, frequencies)
plt.xticks(pos, alphab, rotation=90)
plt.show()
but I get the following:
how could I get this?
The lists, are length distribution, e.g, 172 appears 24 times,..., 465 appear 129 times.
Thanks for your help.
option 1
Let plt figure it out
plt.bar(pos, frequencies)
# plt.xticks(pos, alphab, rotation=90)
plt.show()
option 2
mess with the steps
plt.bar(pos, frequencies)
plt.xticks(pos[::50], alphab, rotation=90)
plt.show()

show origin axis (x,y) in matplotlib plot

I have following simple plot, and I would like to display the origin axis (x, y). I already have grid, but I need the x, y axis to be emphasized.
this is my code:
x = linspace(0.2,10,100)
plot(x, 1/x)
plot(x, log(x))
axis('equal')
grid()
I have seen this question. The accepted answer suggests to use "Axis spine" and just links to some example. The example is however too complicated, using subplots. I am unable to figure out, how to use "Axis spine" in my simple example.
Using subplots is not too complicated, the spines might be.
Dumb, simple way:
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.2,10,100)
fig, ax = plt.subplots()
ax.plot(x, 1/x)
ax.plot(x, np.log(x))
ax.set_aspect('equal')
ax.grid(True, which='both')
ax.axhline(y=0, color='k')
ax.axvline(x=0, color='k')
And I get:
(you can't see the vertical axis since the lower x-limit is zero.)
Alternative using simple spines
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(0.2,10,100)
fig, ax = plt.subplots()
ax.plot(x, 1/x)
ax.plot(x, np.log(x))
ax.set_aspect('equal')
ax.grid(True, which='both')
# set the x-spine (see below for more info on `set_position`)
ax.spines['left'].set_position('zero')
# turn off the right spine/ticks
ax.spines['right'].set_color('none')
ax.yaxis.tick_left()
# set the y-spine
ax.spines['bottom'].set_position('zero')
# turn off the top spine/ticks
ax.spines['top'].set_color('none')
ax.xaxis.tick_bottom()
Alternative using seaborn (my favorite)
import numpy as np
import matplotlib.pyplot as plt
import seaborn
seaborn.set(style='ticks')
x = np.linspace(0.2,10,100)
fig, ax = plt.subplots()
ax.plot(x, 1/x)
ax.plot(x, np.log(x))
ax.set_aspect('equal')
ax.grid(True, which='both')
seaborn.despine(ax=ax, offset=0) # the important part here
Using the set_position method of a spine
Here are the docs for a the set_position method of spines:
Spine position is specified by a 2 tuple of (position type, amount).
The position types are:
'outward' : place the spine out from the data area by the specified number of points. (Negative values specify placing the
spine inward.)
'axes' : place the spine at the specified Axes coordinate (from
0.0-1.0).
'data' : place the spine at the specified data coordinate.
Additionally, shorthand notations define a special positions:
'center' -> ('axes',0.5)
'zero' -> ('data', 0.0)
So you can place, say the left spine anywhere with:
ax.spines['left'].set_position((system, poisition))
where system is 'outward', 'axes', or 'data' and position in the place in that coordinate system.
Some time has passed since this question was asked. With Matplotlib 3.6.2 it looks like this works:
plt.axhline(0, color='black', linewidth=.5)
plt.axvline(0, color='black', linewidth=.5)
and there are other options.
Let me answer to this (rather old) question for those who will search for it as I just did. Although it suggested working solutions, I consider the (only) provided answer as way too complex, when it comes to such a simple situation like that described in the question (note: this method requires you to specify all axes endpoints).
I found a simple working solution in one of the first tutorials on matplotlib's pyplot. It is sufficient to add the following line after the creation of the plot
plt.axis([xmin, xmax, ymin, ymax])
as in the following example:
from matplotlib import pyplot as plt
xs = [1,2,3,4,5]
ys = [3,5,1,2,4]
plt.scatter(xs, ys)
plt.axis([0,6,0,6]) #this line does the job
plt.show()
which produces the following result: