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

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

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

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

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:

How to remove scientific notation from a log-log plot? [duplicate]

This question already has answers here:
Matplotlib log scale tick label number formatting
(6 answers)
Closed 2 years ago.
I'd like the y axis to show only the number 100, 200, and 300, and not in scientific notation. Any thoughts?
Current plot
Simplified code:
from matplotlib import pyplot as plt
import numpy as np
x = np.logspace(2, 6, 20)
y = np.logspace(np.log10(60), np.log10(300), 20)
plt.scatter(x, y[::-1])
plt.xscale('log')
plt.yscale('log')
plt.show()
The major and minor locators determine the positions of the ticks. The standard positions are set via the AutoLocator. The NullLocator removes them. A MultipleLocator(x) shows ticks every multiple x.
For the y axis, setting standard tick positions shows the ticks at the top closer to each other, as determines by the log scale. Doing the same for the x axis, however, due to the large range, would put them too close together. So, for the x axis the positions determined by the LogLocator can stay in place.
The formatters control how the ticks should be displayed. The ScalarFormatter sets the default way. There is an option scilimits that determines for which ranges of values a scientific notation should be used. As 1.000.000 usually gets displayed as 1e6, setting scilimits=(-6,9) avoids this.
from matplotlib import pyplot as plt
from matplotlib import ticker
import numpy as np
x = np.logspace(2, 6, 20)
y = np.logspace(np.log10(60), np.log10(300), 20)
plt.scatter(x, y[::-1])
plt.xscale('log')
plt.yscale('log')
ax = plt.gca()
# ax.xaxis.set_major_locator(ticker.AutoLocator())
ax.xaxis.set_minor_locator(ticker.NullLocator()) # no minor ticks
ax.xaxis.set_major_formatter(ticker.ScalarFormatter()) # set regular formatting
# ax.yaxis.set_major_locator(ticker.AutoLocator()) # major y tick positions in a regular way
ax.yaxis.set_major_locator(ticker.MultipleLocator(100)) # major y tick positions every 100
ax.yaxis.set_minor_locator(ticker.NullLocator()) # no minor ticks
ax.yaxis.set_major_formatter(ticker.ScalarFormatter()) # set regular formatting
ax.ticklabel_format(style='sci', scilimits=(-6, 9)) # disable scientific notation
plt.show()

matplotlib figure with logarithmic axis but ticks without scientific/exponential notation [duplicate]

This question already has an answer here:
Matplotlib: setting x-limits also forces tick labels?
(1 answer)
Closed 5 years ago.
I am making a figure where the x-axis should be logarithmically spaced, but I want to manually set the tick labels, and I want the tick labels to appear in ordinary '%.2f' notation, not exponential notation. The following solution based on Matplotlib - logarithmic scale, but require non-logarithmic labels suggests to use ScalarFormatter, but does not work with matplotlib 2.0:
x = np.logspace(2, 3, 100)
y = x
fig, ax = plt.subplots(1, 1)
xscale = ax.set_xscale('log')
ax.set_xticks((100, 200, 300, 500))
xlim = ax.set_xlim(100, 1000)
from matplotlib.ticker import ScalarFormatter
ax.get_xaxis().set_major_formatter(ScalarFormatter())
__=ax.plot(x, y)
The use of a ScalarFormatter is sure possible. You would then need to make sure that no minor ticklabels are shown as seen in this question: Matplotlib: setting x-limits also forces tick labels?
In your case the code would then look like:
import matplotlib.pyplot as plt
import numpy as np
x = np.logspace(2, 3, 100)
y = x
fig, ax = plt.subplots(1, 1)
xscale = ax.set_xscale('log')
ax.set_xticks((100, 200, 300, 500))
xlim = ax.set_xlim(100, 1000)
import matplotlib.ticker
ax.get_xaxis().set_major_formatter(matplotlib.ticker.ScalarFormatter())
ax.get_xaxis().set_minor_formatter(matplotlib.ticker.NullFormatter())
__=ax.plot(x, y)
plt.show()
Because you are hard-coding the min and max for the axis, it looks like you are trying to create the graph one-off rather than programatically for more general data. In this case, and especially because you are already getting a reference to the x-xais, you could place the tick label strings in a list and use the axis method set_ticklabels. In general, see the API for axis and tick objects.

Categories

Resources