How to set X and Y intervals for matplotlib.pypplot.scatter()? - python

I have the following code for plotting two variables 'field_size' and 'field_mean_LAI':
plt.figure(figsize=(20,10))
plt.scatter(df.field_size, df.field_lai_mean)
plt.title("Field Size and LAI Plot")
plt.xlabel("Field Size")
plt.ylabel("Mean LAI")
plt.show()
The outcome is a scatter plot:
"
How can I configure the x and y intervals and change color of the plot?? I am very beginner in python plotting.

So I modified my code like below:
plt.figure(figsize=(20,10))
plt.scatter(df.field_size, df.field_lai_mean)
plt.title("Field Size and LAI Plot")
plt.xlabel("Field Size")
plt.ylabel("Mean LAI")
plt.xticks(np.arange(0.00000,0.00013,step=0.000008))
plt.yticks(np.arange(0,8.5,step=0.5))
plt.show()
Now I have a plot like this:
Just defined the xticks and yticks functions and it is done smoothly! :)

To change the color of plot points, you can use color attribute (see below).
To set limits of both axes, you can pass xlim and ylim parameters
while creating the subplot.
Note also that I passed here also rot parameter, to set x labels rotation.
And to configure x and y intervals, you can use e.g. MultipleLocator,
for both major and minor ticks. There are other locators too,
search the Web for details.
Additional element which you can set is also the grid (like I did).
So you can change your code to:
import matplotlib.pyplot as plt
import matplotlib.ticker as tck
fig = plt.figure(figsize=(10,5))
ax = plt.subplot(xlim=(-0.000003, 0.000123), ylim=(-0.5, 9))
df.plot.scatter(x='field_size', y='field_lai_mean', rot=30, color='r', ax=ax)
plt.title("Field Size and LAI Plot")
plt.xlabel("Field Size")
plt.ylabel("Mean LAI")
ax = plt.gca()
ax.yaxis.set_major_locator(tck.MultipleLocator(2))
ax.yaxis.set_minor_locator(tck.MultipleLocator(0.4))
ax.xaxis.set_major_locator(tck.MultipleLocator(0.00001))
ax.xaxis.set_minor_locator(tck.MultipleLocator(0.0000025))
ax.grid()
plt.show()
Of course, adjust passed values to your needs.
For a very limited set of points, I got the following picture:

Related

fixing the y scale in python matplotlib

I want to draw multiple bar plots with the same y-scale, and so I need the y-scale to be consistent.
For this, I tried using ylim() after yscale()
plt.yscale("log")
plt.ylim(top=2000)
plt.show()
However, python keeps autoscaling the intermittent values depending on my data.
Is there a way to fix this?
overlayed graphs
import numpy as np
import matplotlib.pyplot as plt
xaxis = np.arange(10)
yaxis = np.random.rand(10)*100
fig = plt.subplots(figsize =(10, 7))
plt.bar(xaxis, yaxis, width=0.8, align='center', color='y')
# show graph
plt.yscale("log")
plt.ylim(top=2000)
plt.show()
You can set the y-axis tick labels manually. See yticks for an example. In your case, you will have to do this for each plot to have consistent axes.

Matplotlib: Plot two x axes, one linear and one with logarithmic ticks

(Heavily edited:)
In python matplotlib, I want to plot y against x with two xscales, the lower one with linear ticks and the upper one with logarithmic ticks.
The lower x values are an arbitrary function of the upper ones (in this case the mapping is func(x)=np.log10(1.0+x)). Corollary: The upper x tick positions are the same arbitrary function of the lower ones.
The positions of the data points and the tick positions for both axes must be decoupled.
I want the upper axis's logarithmic tick positions and labels to be as tidy as possible.
What is the best way to produce such a plot?
Related: http://matplotlib.1069221.n5.nabble.com/Two-y-axis-with-twinx-only-one-of-them-logscale-td18255.html
Similar (but unanswered) question?: Matplotlib: how to set ticks of twinned axis in log plot
Could be useful: https://stackoverflow.com/a/29592508/1021819
You may find Axes.twiny() and Axes.semilogx() useful.
import numpy as np
import matplotlib.pyplot as plt
fig, ax1 = plt.subplots()
x = np.arange(0.01, 10.0, 0.01) # x-axis range
y = np.sin(2*np.pi*x) # simulated signal to plot
ax1.plot(x, y, color="r") # regular plot (red)
ax1.set_xlabel('x')
ax2 = ax1.twiny() # ax1 and ax2 share y-axis
ax2.semilogx(x, y, color="b") # semilog plot (blue)
ax2.set_xlabel('semilogx')
plt.show()
Here is an attempt at an answer after speaking to a few people and with thanks to #BusyBeaver.
I agree the question was ill-posed and will amend it to clarify (help welcome!).
I do think this is a useful one to have written down on stackoverflow.
Code:
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import AutoMinorLocator
# Necessary functions
def tick_function(x):
"""Specify tick format"""
return ["%2.f" % i for i in x]
def func(x):
"""This can be anything you like"""
funcx=np.log10(1.0+x)
return funcx
z=np.linspace(0.0,4.0,20)
np.random.seed(seed=1234)
y=np.random.normal(10.0,1.0,len(z))
# Set up the plot
fig,ax1 = subplots()
ax1.xaxis.set_minor_locator(AutoMinorLocator())
ax1.yaxis.set_minor_locator(AutoMinorLocator())
# Set up the second axis
ax2 = ax1.twiny()
# The tick positions can be at arbitrary positions
zticks=np.arange(z[0],z[-1]+1)
ax2.set_xticks(func(zticks))
ax2.set_xticklabels(tick_function(zticks))
ax2.set_xlim(func(z[0]),func(z[-1]))
ax1.set_ylim(5.0,15.0)
ax1.set_xlabel(r'$\log_{10}\left(1+z\right)$')
ax2.set_xlabel(r'$z$')
ax1.set_ylabel('amplitude/arb. units')
plt.tick_params(axis='both',which = 'major', labelsize=8, width=2)
plt.tick_params(axis='both',which = 'minor', labelsize=8, width=1)
_=ax1.plot(func(z),y,'k.')
plt.savefig('lnopz2.png')
I am not sure how to control the upper ax2 minor ticks (e.g. every 0.5).

Matplotlib graph expand the x axis

I have the following .
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468]
y_values_S3 = [2.3,4.6,9.1,19,39,156]
xticks=['2^6','2^7','2^8','2^9','2^10','2^12']
plt.plot(x_values, y_values_ST,'-gv')
plt.plot(x_values, y_values_S3,'-r+')
plt.legend(['ST','S^3'], loc='upper left')
plt.xticks(x_values,xticks)
fig.suptitle('Encrypted Query Size Overhead')
plt.xlabel('Query size')
plt.ylabel('Size in KB')
plt.grid()
fig.savefig('token_size_plot.pdf')
plt.show()
1)How i can delete the last gap as shown after 2^12?
2)How i can spread more the values in the x axis such that the first two values are not overlapped?
1)How i can delete the last gap as shown after 2^12?
Set the limits explicitly, e.g.:
plt.xlim(2**5.8, 2**12.2)
2)How i can spread more the values in the x axis such that the first two values are not overlapped?
You seem to want a log plot. Use pyplot.semilog(), or set the log scale on the x-axis (base 2 seems appropriate in your case):
plt.xscale('log', basex=2)
Note that in this case you don't even have to set the 2^* ticks manually, they will be created this way automatically.
1.Using autoscale, specify the axes, or alternately you can use plt.axis('tight') for both the axes. 2.Using log scaled x-axis. Code below:
import matplotlib.pyplot as plt
fig = plt.figure()
x_values = [2**6,2**7,2**8,2**9,2**10,2**12]
y_values_ST = [7.3,15,29,58,117,468]
y_values_S3 = [2.3,4.6,9.1,19,39,156]
xticks=['2^6','2^7','2^8','2^9','2^10','2^12']
ax = plt.gca()
ax.set_xscale('log')
plt.plot(x_values, y_values_ST,'-gv')
plt.plot(x_values, y_values_S3,'-r+')
plt.legend(['ST','S^3'], loc='upper left')
plt.xticks(x_values,xticks)
fig.suptitle('Encrypted Query Size Overhead')
plt.xlabel('Query size')
plt.ylabel('Size in KB')
plt.autoscale(enable=True, axis='x', tight=True)#plt.axis('tight')
plt.grid()
fig.savefig('token_size_plot.pdf')
plt.show()

Plot multiple y-axis AND colorbar in matplotlib

I am trying to produce a scatter plot that has two different y-axes and also a colorbar.
Here is the pseudo-code used:
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax1 = fig.add_subplot(111)
plt.scatter(xgrid,
ygrid,
c=be, # set colorbar to blaze efficiency
cmap=cm.hot,
vmin=0.0,
vmax=1.0)
cbar = plt.colorbar()
cbar.set_label('Blaze Efficiency')
ax2 = ax1.twinx()
ax2.set_ylabel('Wavelength')
plt.show()
And it produces this plot:
My question is, how do you use a different scale for the "Wavelength" axes, and also, how do you move the colorbar more to right so that it is not in the Wavelength's way?
#OZ123 Sorry that I took so long to respond. Matplotlib has extensible customizability, sometimes to the point where you get confused to what you are actually doing. Thanks for the help on creating separate axes.
However, I didn't think I needed that much control, and I ended up just using the PAD keyword argument in
fig.colorbar()
and this provided what I needed.
The pseudo-code then becomes this:
#!/usr/bin/python
import matplotlib.pyplot as plt
from matplotlib import cm
fig = plt.figure()
ax1 = fig.add_subplot(111)
mappable = ax1.scatter(xgrid,
ygrid,
c=be, # set colorbar to blaze efficiency
cmap=cm.hot,
vmin=0.0,
vmax=1.0)
cbar = fig.colorbar(mappable, pad=0.15)
cbar.set_label('Blaze Efficiency')
ax2 = ax1.twinx()
ax2.set_ylabel('Wavelength')
plt.show()
Here is to show what it looks like now::
the plt.colorbar() is made for really simple cases, e.g. not really thought for a plot with 2 y-axes.
For a fine grained control of the colorbar location and properties you should almost always rather work with colorbar specifying on which axes you want to plot the colorbar.
# on the figure total in precent l b w , height
cbaxes = fig.add_axes([0.1, 0.1, 0.8, 0.05]) # setup colorbar axes.
# put the colorbar on new axes
cbar = fig.colorbar(mapable,cax=cbaxes,orientation='horizontal')
Note that colorbar takes the following keywords:
keyword arguments:
cax
None | axes object into which the colorbar will be drawn ax
None | parent axes object from which space for a new
colorbar axes will be stolen
you could also see here a more extended answer of mine regarding figure colorbar on separate axes.

In matplotlib, how do you display an axis on both sides of the figure?

I want to draw a plot with matplotlib with axis on both sides of the plot, similar to this plot (the color is irrelevant to this question):
How can I do this with matplotlib?
Note: contrary to what is shown in the example graph, I want the two axis to be exactly the same, and want to show only one graph. Adding the two axis is only to make reading the graph easier.
You can use tick_params() (this I did in Jupyter notebook):
import matplotlib.pyplot as plt
bar(range(10), range(10))
tick_params(labeltop=True, labelright=True)
Generates this image:
UPD: added a simple example for subplots. You should use tick_params() with axis object.
This code sets to display only top labels for the top subplot and bottom labels for the bottom subplot (with corresponding ticks):
import matplotlib.pyplot as plt
f, axarr = plt.subplots(2)
axarr[0].bar(range(10), range(10))
axarr[0].tick_params(labelbottom=False, labeltop=True, labelleft=False, labelright=False,
bottom=False, top=True, left=False, right=False)
axarr[1].bar(range(10), range(10, 0, -1))
axarr[1].tick_params(labelbottom=True, labeltop=False, labelleft=False, labelright=False,
bottom=True, top=False, left=False, right=False)
Looks like this:
There are a couple of relevant examples in the online documentation:
Two Scales (seems to do exactly what you're asking for)
Dual Fahrenheit and Celsius
I've done this previously using the following:
# Create figure and initial axis
fig, ax0 = plt.subplots()
# Create a duplicate of the original xaxis, giving you an additional axis object
ax1 = ax.twinx()
# Set the limits of the new axis from the original axis limits
ax1.set_ylim(ax0.get_ylim())
This will exactly duplicate the original y-axis.
Eg:
ax = plt.gca()
plt.bar(range(3), range(1, 4))
plt.axhline(1.75, color="gray", ls=":")
twin_ax = ax.twinx()
twin_ax.set_yticks([1.75])
twin_ax.set_ylim(ax.get_ylim())

Categories