pyplot: loglog() with base e - python

Python (and matplotlib) newbie here coming over from R, so I hope this question is not too idiotic. I'm trying to make a loglog plot on a natural log scale. But after some googling I cannot somehow figure out how to force pyplot to use a base e scale on the axes. The code I have currently:
import matplotlib.pyplot as pyplot
import math
e = math.exp(1)
pyplot.loglog(range(1,len(degrees)+1),degrees,'o',basex=e,basey=e)
Where degrees is a vector of counts at each value of range(1,len(degrees)+1). For some reason when I run this code, pyplot keeps giving me a plot with powers of 2 on the axes. I feel like this ought to be easy, but I'm stumped...
Any advice is greatly appreciated!

When plotting using plt.loglog you can pass the keyword arguments basex and basey as shown below.
From numpy you can get the e constant with numpy.e (or np.e if you import numpy as np)
import numpy as np
import matplotlib.pyplot as plt
# Generate some data.
x = np.linspace(0, 2, 1000)
y = x**np.e
plt.loglog(x,y, basex=np.e, basey=np.e)
plt.show()
Edit
Additionally if you want pretty looking ticks you can use matplotlib.ticker to choose the format of your ticks, an example of which is given below.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
x = np.linspace(1, 4, 1000)
y = x**3
fig, ax = plt.subplots()
ax.loglog(x,y, basex=np.e, basey=np.e)
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
ax.xaxis.set_major_formatter(mtick.FuncFormatter(ticks))
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()

It can also works for semilogx and semilogy to show them in e and also change their name.
import matplotlib.ticker as mtick
fig, ax = plt.subplots()
def ticks(y, pos):
return r'$e^{:.0f}$'.format(np.log(y))
plt.semilogy(Time_Series, California_Pervalence ,'gray', basey=np.e )
ax.yaxis.set_major_formatter(mtick.FuncFormatter(ticks))
plt.show()
Take a look at the image.

Related

how to plot some lists with different shape?

I have some lists that each of which has a different shape and I would like to plot all of them together in one polar scatter plot. I also tried to use iter tools but I could not find the solution.
import numpy as np
import matplotlib.pyplot as plt
a1=[1,2,3,4,5,6]
a2=[2,3,5,6]
a3=[1,2,3]
a4=[1,2,3,4,4,56,7,8]
ax1 = plt.subplot(111,polar= True)
for i in range (0,3):
theta = 4 * np.pi * np.random.rand(len(a[i]))
ax1.set_ylim(0,0.1)
ax1.set_rlabel_position(180)
for i in range (0,3):
ax1.scatter(theta,a[i], cmap='hsv', alpha=0.5)
Be carefull i modified your lists for a better visual exmaple!
I hope I understood your question correctly...
import numpy as np
import matplotlib.pyplot as plt
a1=[1,2,3,4,5,6]
a2=[2,3,5,6]
a3=[1,2,3]
a4=[1,2,3,4,4,7,7,8]
ax1 = plt.subplot(111,polar= True)
for onelist in [a1,a2,a3,a4]:
theta_list = np.linspace(0,2*np.pi,len(onelist))
ax1.plot(theta_list,onelist,marker="x")
plt.show()

How to make horizontal linechart with categorical variables and timeseries?

I want to replicate plots from this paper: https://www.ncbi.nlm.nih.gov/pmc/articles/PMC5000555/pdf/nihms774453.pdf I'm particularly interested in plot on page 16, right panel. I tried to do this in matplotlib but it seems to me that there is no way to access lines in linecollection.
I don't know how to change the color of the each line, according to the value at every index. I'd like to eventually get something like here: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/multicolored_line.html but for every line, according to the data.
this is what I tried:
the data in numpy array: https://pastebin.com/B1wJu9Nd
import pandas as pd, numpy as np
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib import colors as mcolors
%matplotlib inline
base_range = np.arange(qq.index.max()+1)
fig, ax = plt.subplots(figsize=(12,8))
ax.set_xlim(qq.index.min(), qq.index.max())
# ax.set_ylim(qq.columns[0], qq.columns[-1])
ax.set_ylim(-5, len(qq.columns) +5)
line_segments = LineCollection([np.column_stack([base_range, [y]*len(qq.index)]) for y in range(len(qq.columns))],
cmap='viridis',
linewidths=(5),
linestyles='solid',
)
line_segments.set_array(base_range)
ax.add_collection(line_segments)
axcb = fig.colorbar(line_segments)
plt.show()
my result:
what I want to achieve:

Python3.6 - Plotting lat/long co-ordinates on Matplotlib [duplicate]

This question already has an answer here:
Difference in plotting with different matplotlib versions
(1 answer)
Closed 4 years ago.
This is my first time using Matplotlib. I have a series of latitude and longitude co-ordinates in two lists, and I want to represent these in a meaningful manner. I would not like to use Basemap for several reasons.
lat = ['35.905333', '35.896389', '35.901281', '35.860491', '35.807607', '35.832267', '35.882414', '35.983794', '35.974463', '35.930951']
long = ['14.471970', '14.477780', '14.518173', '14.572245', '14.535320', '14.455894', '14.373217', '14.336096', '14.351006', '14.401137']
I am trying to represent these in a meaningful manner using Matplotlib.
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
plt.scatter(lat, long)
plt.show()
However my figure is as follows:
I am unable to set the axis in order to obtain a meaningful representation of these coordinates. How can this be done? What am I doing wrong?
I am looking for something like this:
import numpy as np
import matplotlib.pyplot as plt
N = 50
x = np.random.rand(N)
y = np.random.rand(N)
plt.scatter(x, y)
plt.show()
I get the expected outcome.
I have also tried to plot on a cartesian coordinate system.
EDIT:
As per the comment below:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
plt.scatter(lat, long)
plt.axis('square')
plt.show()
As mentioned in the comment, change the type to float:
import numpy as np
import matplotlib.pyplot as plt
lat = np.array(['35.905333', '35.896389', '35.901281', '35.860491', '35.807607',
'35.832267', '35.882414', '35.983794', '35.974463', '35.930951'], dtype=float)
long = np.array(['14.471970', '14.477780', '14.518173', '14.572245', '14.535320',
'14.455894', '14.373217', '14.336096', '14.351006', '14.401137'], dtype=float)
fig, ax = plt.subplots(figsize=(10, 6))
ax.scatter(lat, long)
# ax.axis('equal')
plt.show()

How to change plot properties of statsmodels qqplot? (Python)

So I am plotting a normal Q-Q plot using statsmodels.graphics.gofplots.qqplot().
The module uses matplotlib.pyplot to create figure instance. It plots the graph well.
However, I would like to plot the markers with alpha=0.3.
Is there a way to do this?
Here is a sample of code:
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
test = np.random.normal(0,1, 1000)
sm.qqplot(test, line='45')
plt.show()
And the output figure:
You can use statsmodels.graphics.gofplots.ProbPlot class which has qqplot method to pass matplotlib pyplot.plot **kwargs.
import numpy as np
import statsmodels.api as sm
import matplotlib.pyplot as plt
test = np.random.normal(0, 1, 1000)
pp = sm.ProbPlot(test, fit=True)
qq = pp.qqplot(marker='.', markerfacecolor='k', markeredgecolor='k', alpha=0.3)
sm.qqline(qq.axes[0], line='45', fmt='k--')
plt.show()
qqplot returns a figure object which can be used to get the lines which can then be modified using set_alpha
fig = sm.qqplot(test, line='45');
# Grab the lines with blue dots
dots = fig.findobj(lambda x: hasattr(x, 'get_color') and x.get_color() == 'b')
[d.set_alpha(0.3) for d in dots]
Obviously you have a bit of overlap of the dots so even though they have a low alpha value, where they are piled on top of one another they look to be more opaque.

matplotlib.pyplot.ticklabel_format has no effect on the figure

as the title suggests, this is a straightforward question: ticklabel_format simply has no effect whatsoever on my figure.
here's the script:
import sys
import math
import yaml
import numpy as np
import matplotlib.pyplot as plt
dwarf = sys.argv[1]
pts = np.empty([100,100])
fig = plt.figure()
fig.suptitle('J value - %s'%dwarf,fontsize=18)
m = plt.imshow(pts,cmap='rainbow',extent=[-2,2,5,9])
plt.xlabel(r'$r_s [kpc]$',fontsize=18)
plt.ylabel(r'$\rho_s [M_{sun} kpc^{-3}]$',fontsize=18)
plt.ticklabel_format(style='sci',axis='x',scilimits=(-2,2))
plt.ticklabel_format(style='sci',axis='y',scilimits=(5,9))
plt.grid()
cx = plt.colorbar(m,pad=0)
cx.set_label(r'$log_{10}(J(\rho_s,r_s))$',fontsize=18)
plt.savefig('output/gridJ_%s.png'%dwarf,dpi=100,format='png')
plt.show()
on the produced plot, the ticks on the axes are simply the values dictated by extent kwarg in plt.imshow and not the nice scientific notation 10**n I would like it to have.
Any idea why it's misbehaving? Thank you
Just use matplotlib.pyplot.ylim or matplotlib.pyplot.xlim to set the limits.

Categories