Matplotlib squeezing x labels [duplicate] - python

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')

Related

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())

Selectively marking horizontal regions in Seaborn Plot (Python) [duplicate]

This question already has answers here:
How to highlight specific x-value ranges
(2 answers)
Closed 1 year ago.
I went through the examples in the matplotlib documentation, but it wasn't clear to me how I can make a plot that fills the area between two specific vertical lines.
For example, say I want to create a plot between x=0.2 and x=4 (for the full y range of the plot). Should I use fill_between, fill or fill_betweenx?
Can I use the where condition for this?
It sounds like you want axvspan, rather than one of the fill between functions. The differences is that axvspan (and axhspan) will fill up the entire y (or x) extent of the plot regardless of how you zoom.
For example, let's use axvspan to highlight the x-region between 8 and 14:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, alpha=0.5, color='red')
plt.show()
You could use fill_betweenx to do this, but the extents (both x and y) of the rectangle would be in data coordinates. With axvspan, the y-extents of the rectangle default to 0 and 1 and are in axes coordinates (in other words, percentages of the height of the plot).
To illustrate this, let's make the rectangle extend from 10% to 90% of the height (instead of taking up the full extent). Try zooming or panning, and notice that the y-extents say fixed in display space, while the x-extents move with the zoom/pan:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.plot(range(20))
ax.axvspan(8, 14, ymin=0.1, ymax=0.9, alpha=0.5, color='red')
plt.show()

Change Parameters of individual xtick Labels in Matplotlib [duplicate]

This question already has an answer here:
Formatting only selected tick labels
(1 answer)
Closed 2 years ago.
I would like to have more control over individual x-axis labels using matplotlib. This question helped me a bit, but I still would like to do more. For instance I would like to bold, change font style and font size.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(1,10,10)
y = x**2
fig, ax = plt.subplots(figsize=(5,5))
plt.plot(x,y)
ax.get_xticklabels()[3].set_color('red')
I do understand with something like the following line, I have more parameters to control, but this will change all the labels, not an individual one:
ax.set_xticklabels(x, rotation=45, weight='light')
You can still use all the functionalities
ax.get_xticklabels()[3].set_color('red')
ax.get_xticklabels()[3].set_fontsize(20)
ax.get_xticklabels()[3].set_weight("bold")
ax.get_xticklabels()[3].set_rotation(45)
The bold function does work. See the difference:

In Matplotlib, what axis attribute specifies the spacing between ticks? [duplicate]

This question already has answers here:
Changing the tick frequency on the x or y axis
(13 answers)
Closed 4 years ago.
When generating a Matplotlib line or scatter plot, what axis attribute specifies the spacing between ticks? I do not want to explicitly specify where each tick should be as prompted by this related question
ax.ticks(np.arange(-100, 100, 5))
What is the matplotlib axis attribute that controls the tick spacing? It should behave something like the following.
ax.set_x_tick_spacing(5)
This would use the same default xlim and origin point (usually 0) as the default settings.
A more recent answer to the related question illustrates using the matplotlib.ticker.MultipleLocator object. The axis ticks are this type of matplotlib object. Here is an example of it's use.
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(5))
will place ticks 5 units apart on the x-axis, and
ax.xaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(1))
will place minor ticks 1 unit apart on the x-axis.
Here is an example from the matplotlib Plotting Cookbook
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
X = np.linspace(-15, 15, 1024)
Y = np.sinc(X)
ax = plt.axes()
ax.xaxis.set_major_locator(matplotlib.ticker.MultipleLocator(5))
ax.xaxis.set_minor_locator(matplotlib.ticker.MultipleLocator(1))
plt.plot(X, Y, c = 'k')
plt.show()

Logarithmic y axis makes tick labels disappear [duplicate]

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')

Categories

Resources