How do I make my plot look like this with matplotlib? - python-3.x

So right now I'm trying to simulate a Poisson process for an assignment, here's the code so far:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
y = np.arange(0,21,1)
x = np.cumsum(np.random.exponential(2,21))
print(y)
print(x)
sns.set()
plt.plot(x,y)
plt.show()
The problem arises when I try plotting it. The code above, as expected, produces a normal matplotlib plot that looks like this:
However I need it to look like this:
Is there an easy way of doing it? I tried messing with bar plots but was unable to produce something that looks good.

The graph that you are wanting to plot is called as step plot in matplotlib. In order to plot it replace plt.plot(x,y) with plt.step(x,y)
So, your code becomes:
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
y = np.arange(0,21,1)
x = np.cumsum(np.random.exponential(2,21))
print(y)
print(x)
sns.set()
plt.step(x,y)
plt.show()

Related

Python matplotlib custom colorbar for plotted lines with manually assigned colors

I'm trying to define a colorbar for the following type of plot.
import matplotlib.pyplot as plt
import numpy as np
for i in np.arange(0,10,0.1):
plt.plot(range(10),np.ones(10)*i,c=[i/10.,0.5,0.25])
plt.show()
This is just a simplified version of my actual data, but basically, I'd like a series of lines plotted and colored by another variable with a colorbar key. This is easy to do in scatter, but I can't get scatter to plot connected lines. Points are too clunky. I know this sounds like basic stuff, but I'm having a helluva time finding a simple solution ... what obvious solution am I missing?
You can build a custom color map and a mappable from it, then pass to colorbar:
from matplotlib.cm import ScalarMappable
from matplotlib.colors import Normalize
import matplotlib.colors as mcolors
color_list = [(i/10, 0.5,0.25) for i in np.arange(0,10,0.1)]
cmap = mcolors.LinearSegmentedColormap.from_list("my_colormap", color_list)
cmappable = ScalarMappable(norm=Normalize(0,10), cmap=cmap)
plt.figure(figsize=(10,10))
for j,i in enumerate(np.arange(0,10,0.1)):
plt.plot(range(10),np.ones(10)*i,c=color_list[j])
plt.colorbar(cmappable)
plt.show()
Output:

Matplotlib function visualtization changing with precision

So I was trying to map out some math functions in 3d using matplotlib when I noticed something... The 3d plot suddenly changed (more like broke) when I tried to fix a previous issue wherein I was encountering some 'missing surface' - a gap in the plot. The main question is this -- Is the 3d plot not showing the two peaks on higher precision due to some inherent computing limitations of Axes3d or some other reason? Also a secondary question -- Why am I encountering 'missing surfaces' near +1.25 and -1.25 in lower precision plot?
I have tried googling for it and referred a few posts but nothing came ot except more questions.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
X=np.arange(-2,+2,0.025)
## Use np.arange(-5,+5,0.25) to experience the 'surface loss' I mention but otherwise correct 2 spike plot at each of (0,-1) and (0,+1) for both X and Y
Y=np.arange(-2,+2,0.025)
X,Y=np.meshgrid(X,Y)
R=1+X**2-Y**2
S=R**2+4*(X**2)*(Y**2)
Z=R/S
fig=plt.figure()
ax=Axes3D(fig)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.viridis,norm=mpl.colors.Normalize(vmin=-1.,vmax=1.))
##NORMALIZE Was essential to get the proper color range
plt.show()
plt.savefig('art3d.jpeg',bbox_inches='tight')
plt.savefig('art3d.svg',bbox_inches='tight')
The ideal result should be like this (shows the func and the plot)
https://i.stack.imgur.com/kVnYc.png
The two plots I'm getting could be seen when the code is run as I can't seem to add images presumably because of low reputation :(
Any and all help is appreciated.Thanks in advance.
First note that the function in use is different from the wolfram alpha output. So let's use the function shown in the screenshot. Then you can limit the data to the range you want to show.
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D
X = np.arange(-2,+2,0.025)
Y=np.arange(-2,+2,0.025)
X,Y=np.meshgrid(X,Y)
Z = -2*X*Y / ((2*X*Y)**2 + (X**2 - Y**2 + 1)**2)
Z[(Z < -1)] = -1
Z[(Z > 1)] = 1
fig=plt.figure()
ax=Axes3D(fig)
ax.plot_surface(X,Y,Z,rstride=1,cstride=1,cmap=cm.viridis,norm=mpl.colors.Normalize(vmin=-1.,vmax=1.))
plt.show()

Python exponential plot is wrong

I am new using python and try to do some plots. I realized, that a plot of a bump function is incorrect. I have no idea how python came to this result.
This is my 'code'
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import matplotlib.pyplot as plt
class MainBody():
x = np.linspace(0.0001,99.9999,1000)
result = np.exp((-1.0)/(x*(100.0-x)))
plt.plot(x,result)
plt.show()
I got this result
but I should get this
I know that Python is powerful but I think such simple things should work without occuring such errors, where is my mistake?
Thank you
Matthias
Use plt.ylim to set the y-limits. Otherwise, by default, matplotlib will try to show the entire dataset, whose y-limits go roughly from 0 to 1:
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0.0001,99.9999,1000)
result = np.exp((-1.0)/(x*(100.0-x)))
plt.plot(x,result)
plt.ylim(0.9975, 0.9999)
plt.show()

add a line to matplotlib subplots

I would like to do a subplot of two figures with matplotlib and add a horizontal line in both. This is probably basic, but I don't know how to specify that one of the lines should be drawn in the first figure, they both end up in the last one. e.g.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.rand(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0])
l1=plt.axhline(0.5,color='black',ls='--')
l1.set_label('l1')
f2= s1.plot(ax=axes[1])
l2=plt.axhline(0.7,color='red',ls='--')
l2.set_label('l2')
plt.legend()
axhline does not have "ax" as an argument, as the pandas plot function does. So this would work:
l1=plt.axhline(0.5,color='black',ls='--',ax=axes[0])
I read the examples in matplotlib and I tried with this other option that does not work either (probably for good reasons)
axes[0].plt.axhline(0.5,color='black',ls='--')
How should I do to draw lines in subplots? Ideally with a legend Thanks!
with the help of #Nick Becker I answered my own "syntax" question.
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
%matplotlib inline
s1= pd.Series(np.random.rand(10))
s2= pd.Series(np.random.randn(10))
fig, axes = plt.subplots(nrows=2,ncols=1)
f1= s1.plot(ax=axes[0],label='s1')
l1=axes[0].axhline(0.5,color='black',ls='--')
l1.set_label('l1')
axes[0].legend(loc='best')
f2= s1.plot(ax=axes[1],label='s2')
l2=axes[1].axhline(0.5,color='black',ls='--')
l2.set_label('l2')
axes[1].legend(loc='best')

Plot shows automatically

I have a strange problem when plotting with matplotlib
Here is a sample code
from matplotlib.pyplot import *
for i in range(100):
plot(range(10))
xlabel("x")
This code will pop-up 100 times a figure. It seems that show() is called automatocally.
How can I make sure that after the plots no plot-windows are showed?
You can force it to use only one figure like:
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
for i in range(100):
ax.plot(range(10))
ax.set_xlabel("x")

Resources