How to force a graph within a grid in matplotlib? - matplotlib

I have a grid that looks like this
fig = plt.figure()
ax = fig.gca()
ax.set_xticks(numpy.arange(-5,6,1))
ax.set_yticks(numpy.arange(-5,6,1))
plt.grid(True)
When plotting an exponential function, obviously the function's values grow larger than the grid very quickly, and my grid ticks get distorted. I want the grid to be fixed, and only that part of the function to be graphed which fits inside of the grid. Is this possible?
Thanks in advance.

You can set the limits of the axes:
fig = plt.figure()
ax = fig.gca()
# Exponential plot:
x = linspace(-5, 5, 100)
y = power(2, x)
ax.plot(x, y)
ax.set_xticks(numpy.arange(-5,6,1))
ax.set_yticks(numpy.arange(-5,6,1))
ax.set_xlim(-5, 6)
ax.set_ylim(-5, 6)
plt.grid(True)

Related

Logit scale in Plotly Express

My goal is to get a probability plot with the logit scale using Plotly Express (px).
In Matplotlib (plt) this is possible:
x, y = ([1, 2, 3], [1, 3, 2])
fig, ax = plt.subplots()
ax.scatter(x, y)
ax.set_yscale("logit")
Is there any comparable functionality in px?
The workaround I am trying currently is to get these ticks from plt and give them as parameters to px. That does work, but only changes the tick labels, not the actual scale of the y axis:
ytickvals = ax.get_yticks()
fig = px.scatter(x, y)
layout = dict(
yaxis=dict(
tickmode="array",
tickvals=ytickvals
)
)
fig.update_layout(layout)
How can I set the scale of the Plotly plot to be like the logit scale of Matplotlib?
Plotly API documentation doesn't know the term "logit" and plotly.graph_objects.layout.YAxis seems to not have a way of setting the scale.
PS, bonus question: why do my ticks not get displayed with the suffix using ticksuffix=" %" and showticksuffix="all"?

y and x axis subplots matplotlib

A quite basic question about ticks' labels for x and y-axis. According to this code
fig, axes = plt.subplots(6,12, figsize=(50, 24), constrained_layout=True, sharex=True , sharey=True)
fig.subplots_adjust(hspace = .5, wspace=.5)
custom_xlim = (-1, 1)
custom_ylim = (-0.2,0.2)
for i in range(72):
x_data = ctheta[i]
y_data = phi[i]
y_err = err_phi[i]
ax = fig.add_subplot(6, 12, i+1)
ax.plot(x_data_new, bspl(x_data_new))
ax.axis('off')
ax.errorbar(x_data,y_data, yerr=y_err, fmt="o")
ax.set_xlim(custom_xlim)
ax.set_ylim(custom_ylim)
I get the following output:
With y labels for plots on the first column and x labels for theone along the last line, although I call them off.
Any idea?
As #BigBen wrote in their comment, your issue is caused by you adding axes to your figure twice, once via fig, axes = plt.subplots() and then once again within your loop via fig.add_subplot(). As a result, the first set of axes is still visible even after you applied .axis('off') to the second set.
Instead of the latter, you could change your loop to:
for i in range(6):
for j in range(12):
ax = axes[i,j] # these are the axes created via plt.subplots(6,12,...)
ax.axis('off')
# … your other code here

Dataframe.plot() not working when ax is defined

I am trying to emulate the span selector for the data I have according to the example shown here (https://matplotlib.org/examples/widgets/span_selector.html).
However, my data is in a dataframe & not an array.
When I plot the data by itself with the using the code below
input_month='2017-06'
plt.close('all')
KPI_ue_data.loc[input_month].plot(x='Order_Type', y='#_Days_#_Post_stream')
plt.show()
the data chart is shown perfectly.
However when i am trying to put this into a subplot with the code below (only first two lines are added & ax=ax in the plot line), nothing shows up. I get no error either!!! can anyone help?
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211, facecolor='#FFFFCC')
input_month='2017-06'
plt.close('all')
KPI_ue_data.loc[input_month].plot(x='Order_Type', y='#_Days_#_Post_stream',ax=ax)
plt.show()
I usually just set x, y from the dataframe and use ax.plot(x, y). For your code, it should look something like this:
fig = plt.figure(figsize=(8, 6))
ax = fig.add_subplot(211, facecolor='#FFFFCC')
input_month='2017-06'
#plt.close('all')
x = KPI_ue_data.loc[(input_month), 'Order_Type']
y = KPI_ue_data.loc[(input_month), '#_Days_#_Post_stream']
ax.plot(x, y)
plt.show()

How to stack the graphs in such a way that the share a common scale along x-axis

The following code is for generating the 3 subplots. And on all the 3 subplots scale is mentioned. I want to stack them in such a way that x-axis and y-axis scale appear once like this. Can I get this plot with plt.subplot() or fig.add_axes is compulsory for this? I actually want to do this with subplots because in fig.add_subplot I havve to specify the width and height of each plot that I don't want.
`fig,axes = plt.figure(nrow=3, ncolmn=1)
ax1 = fig.add_subplot(311)
ax2 = fig.add_subplot(312)
ax3 = fig.add_subplot(313)
ind1 =[1,2,3]
ind2 = [4,5,6]
for i in range(len(3)):
data1=np.load(..)
data2=np.load(..)
axes[i].plot(data1, data2)`
Here is one solution using subplots_adjust where you put the space between two plots to 0 using hspace. Also, use sharex=True to have a shared x-axis
fig, axes = plt.subplots(nrows=3, ncols=1,sharex=True)
x = np.linspace(0, 2*np.pi, 100)
y = np.sin(x)
for i, ax in enumerate(axes.ravel()): # or axes.flatten() or axes.flat
ax.plot(x, y, label='File %d' %i)
ax.legend()
fig.text(0.5, 0.01, 'X-label', ha='center')
fig.text(0.01, 0.5, 'Y-label', va='center', rotation='vertical')
plt.tight_layout() # To get a better spacing between the subplots
plt.subplots_adjust(hspace=.0)

Removing frame while keeping axes in pyplot subplots

I am creating a figure with 3 subplots, and was wondering if there is any way of removing the frame around them, while keeping the axes in place?
If you want to remove the axis spines, but not the other information (ticks, labels, etc.), you can do that like so:
fig, ax = plt.subplots(7,1, sharex=True)
t = np.arange(0, 1, 0.01)
for i, a in enumerate(ax):
a.plot(t, np.sin((i + 1) * 2 * np.pi * t))
a.spines["top"].set_visible(False)
a.spines["right"].set_visible(False)
a.spines["bottom"].set_visible(False)
or, more easily, using seaborn:
fig, ax = plt.subplots(7,1, sharex=True)
t = np.arange(0, 1, 0.01)
for i, a in enumerate(ax):
a.plot(t, np.sin((i + 1) * 2 * np.pi * t))
seaborn.despine(left=True, bottom=True, right=True)
Both approaches will give you:
Try plt.box(on=None) It removed only the bounding box (frame) around plot, which is what I was trying to do.
plt.axis('off') removed tick labels and the bounding box, which wasn't what I was looking to accomplish.
You can achieve something like this with the axis('off') method of an axis handle. Is this the kind of thing you are after? (example code below the figure).
fig, ax = plt.subplots(7,1)
t = np.arange(0, 1, 0.01)
for i, a in enumerate(ax):
a.plot(t, np.sin((i+1)*2*np.pi*t))
a.axis('off')
plt.show()
Try
ax.set_frame_on(False)
It removes the box frame around any plot, but the x and y ticks remain.