Logarithmic y axis makes tick labels disappear [duplicate] - python

This question already has answers here:
How to show minor tick labels on log-scale with Matplotlib
(2 answers)
Closed 7 years ago.
Upon adding the line plt.yscale('log') to my simple plotting script
import numpy as np
residuals = np.loadtxt('res_jacobi.txt', skiprows=1)
import matplotlib.pyplot as plt
fig = plt.figure()
steps = np.arange(0, len(residuals), 1)
plt.plot(steps, residuals, label='$S$')
plt.xlabel("Step",fontsize=20)
plt.ylabel("$S$",fontsize=20)
plt.ylim(0.95 * min(residuals), 1.05 * max(residuals))
plt.yscale('log')
plt.savefig('jacobi-res.pdf', bbox_inches='tight', transparent=True)
the y labels disappear.
I'm sure there is simple fix for this but searching did not turn one up. Any help would be much appreciated.

The normal behavior for matplotlib is to only label major tick marks in log-scaling --- which are even orders of magnitude, e.g. {0.1, 1.0}. Your values are all between those. You can:
rescale your axes to larger bounds,
plt.gca().set_ylim(0.1, 1.0)
label the tick-marks manually,
plt.gca().yaxis.set_minor_formatter(FormatStrFormatter("%.2f"))

semilogy works for me.
Change:
plt.plot(steps, residuals, label='$S$')
Into:
plt.semilogy(steps, residuals, label='$S$')
Remove plt.yscale('log')

Related

matplotlib.pyplot.bar plots empty graph [duplicate]

This question already has an answer here:
'missing' bars in matplotlib bar chart
(1 answer)
Closed 5 months ago.
I'm sure I've missed something basic but I can't find anything about this by googling so here goes.
I'm trying to plot a bar chart using matplotlib.pyplot but I keep getting an empty bar chart (with the correct axis but no actual bars).
My minimal code to reproduce this is as follows:
import matplotlib.pyplot as plt
plt.bar(
x=[1288.7, 9386.9, 12086.3, 14785.7, 17485.1, 20184.5, 22883.9, 25596.797],
height=[0.22772277227722773, 0.5, 0.5, 0.4430379746835443, 0.3658696364231903, 0.39693539122862276, 0.4186823730508119, 0.44525257342712926]
)
plt.show()
I'm actually trying to plot some data calculated in pandas using pd.Crosstabs() e.g.
fig, ax = plt.subplots(1,1)
ax.bar(
x=list(df.index),
height=list(df["column1"])
)
But the problem seems to actually be with matplotlib, not with my data.
The problem is that the default bar-width is too small relative to the scale of the x-values. You can set the width as an optional parameter. For example,
import matplotlib.pyplot as plt
plt.bar(
x=[1288.7, 9386.9, 12086.3, 14785.7, 17485.1, 20184.5, 22883.9, 25596.797],
height=[0.22772277227722773, 0.5, 0.5, 0.4430379746835443, 0.3658696364231903, 0.39693539122862276, 0.4186823730508119, 0.44525257342712926],
width = 1e3
)
plt.show()
results in a reasonable graph.

Scaling and Labelling KDE plots [duplicate]

This question already has answers here:
Matplotlib Legends not working
(4 answers)
How to set the y-axis limit
(8 answers)
Closed 1 year ago.
I plotted PDF using kdeplot. I am having a tough time to scale and label the plots.
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
error = np.array([1,2,2,3,4,4,5])
error2 = np.array([3,3,4,4,4,6])
sns.kdeplot(error, color='blue',label='error')
sns.kdeplot(error2, color='red',label='error2')
plt.show()
I want the blue curve to be labelled as 'error' and red curve to be labelled as 'error2'.
Also, I want to scale the y-axis. It should be in the range of 0 to 1 with 0.1 interval. How can I achieve this?
Thanks in advance
To add a legend, just add
plt.legend()
above plt.show(). To set the limit of the axis, use
ax = plt.gca() # get current axis
ax.set_ylim([0, 1])
To set the ticks accordingly, you can use
ax.set_yticks(np.arange(0, 1.1, 0.1))
(All above plt.show())

Matplotlib squeezing x labels [duplicate]

This question already has answers here:
Rotate tick labels in subplot (Pyplot, Matplotlib, gridspec)
(3 answers)
Closed 2 years ago.
I'm trying to plot a lot a data points and the X axis is timestamps. My problem is that for some length Matplotlib automatically squeezes them together and you cannot read the x axis, as shown in the pic:
How can I prevent this from happening? I'm trying to save that plot automatically with savefig(). It is saved to a PNG.
you can specify the X-Ticks with following:
import matplotlib.pyplot as plt
plt.plot(x_values, y_value)
plt.xticks([0,5,10])
The Plot will have less ticks.
WIthout the x-ticks:
With x-ticks:
I found the answer here on the matplotlib site:
https://matplotlib.org/3.1.1/gallery/recipes/common_date_problems.html
fig, ax = plt.subplots()
ax.plot(date, r.close)
# rotate and align the tick labels so they look better
fig.autofmt_xdate()
# use a more precise date string for the x axis locations in the
# toolbar
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
ax.set_title('fig.autofmt_xdate fixes the labels')

Automatically determine plot size matplotlib [duplicate]

This question already has an answer here:
Inconsistent figsize resizing in matplotlib
(1 answer)
Closed 3 years ago.
I am trying to generate a bar chart with lots of bars. If I keep the figsize at defaults, the data is squeezed together and the plot is unusable.
I have the following code snippet to reproduce my problem:
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure(1)
ax = fig.add_subplot(111)
N=100
# Example data
labels = [chr(x) for x in range(N)]
y_pos = np.arange(len(labels))
performance = 3 + 10 * np.random.rand(len(labels))
error = np.random.rand(len(labels))
ax.barh(y_pos, performance, xerr=error, align='center')
ax.set_yticks(y_pos)
ax.set_yticklabels(labels)
ax.set_xlabel('Performance')
ax.set_title('How fast do you want to go today?')
plt.savefig('a.png', bbox_inches='tight')
plt.show()
If I manually set the height of the figure (for example figsize=(8,N*0.2)), the plotted data looks nice, but there is an annoying vertical whitespace before the firs bar and after the last one.
Is there any way to automatically size the plot properly?
One thing I've used is
plt.tight_layout()
it generates less whitespace for subplots, but may work with just 1 plot.
Here's more info:
https://matplotlib.org/users/tight_layout_guide.html
Another thing that may work is aspect auto when showing the plot.
plt.imshow(X, aspect='auto')
Yet another solution is 'scaled' axis
plt.axis('scaled') #this line fits your images to screen
Also if you mean the overall plot size,I generally just pick a generic size that fits, say 15 x 10 on a laptop screen, or 30x20 on a monitor. Guess and test.

Correctly setting the axes limits in matplotlib 3dplots? [duplicate]

This question already has answers here:
Removing axes margins in 3D plot
(2 answers)
Closed 4 years ago.
I'm having an issue with setting limits for my 3d plots in matplotlib; I'm finding that no matter how I set my limits for the x,y, and z axes, the plotting routine for 3dplots adds an extra buffer.
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.axes.set_xlim3d(left=0, right=10)
ax.axes.set_ylim3d(bottom=0, top=10)
ax.axes.set_zlim3d(bottom=0, top=10)
plt.show()
This produces the following plot:
As you can see, the limits are supposed to be at x, y, z = {0, 10} however the 3D plotting always adds a little bit of a buffer to each edge. Does anyone know a way to turn this effect off?
I've also used plt.xlims(); and ax.axes.set_xlims() but they produce the same effect.
I think this is deliberate (see e.g. this), if you try plotting ax.axes.set_xlim3d(left=0.000001, right=9.9999999) then you get no 0 or 10 displayed on your figure.
Even making the numbers as arbitrarily close as possible doesn't work, e.g.
eps = 1e-16
ax.axes.set_xlim3d(left=0.-eps, right=10+eps)
ax.axes.set_ylim3d(bottom=0.-eps, top=10+eps)
ax.axes.set_zlim3d(bottom=0.-eps, top=10+eps)
The best solution I've found is to set the ticks manually and then slightly scale so the overlap is hidden.
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111,projection='3d')
ax.set_xticks([0,2,4,6,8,10])
ax.set_yticks([0,2,4,6,8,10])
ax.set_zticks([0,2,4,6,8,10])
ax.axes.set_xlim3d(left=0.2, right=9.8)
ax.axes.set_ylim3d(bottom=0.2, top=9.8)
ax.axes.set_zlim3d(bottom=0.2, top=9.8)
plt.show()
This gives,
This is pretty hacky but could be made more general (and I always end up setting ticks manually for publication quality figures). Alternatively, it may be better to turn off the lowest grid line or hide the grid...

Categories

Resources