Change Parameters of individual xtick Labels in Matplotlib [duplicate] - python

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:

Related

Seaborn chart in Jupyter notebook ignoring figsize parameter [duplicate]

This question already has answers here:
How to change figuresize using seaborn factorplot
(7 answers)
Closed 1 year ago.
For some reason chart size remains unchanged, although I've changed figsize parameters.
Very appreciate your help :)
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
dt = pd.DataFrame({'col':[26,0,23,7,23,23,22,23,19,22,1,1,11,11,23,14,23,21,11,23,10,11,13,28,18,25,23,28,18,23,18,18,
23,18,23,24,11,28,23,23,23,23,19,23,23,23,23,22,14]})
plt.figure(figsize=(15,6))
sns.displot(dt['col'], kde=True)
plt.show()
This is a result I get
Try rewriting the code in this way:
g=sns.displot(dt['col'], kde=True)
g.fig.set_size_inches(15,6)
You can go through this for further information
Try using the height parameter (in inches) and aspect (as the ratio of widht/height)
you want a figure with an aspect ratio of 2.67
ar = width / height
ar = 16/6
ar = 2.67
Try this line instead:
g=sns.displot(dt['col'], kde=True,height=6,aspect=2.67)

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

How to set x axis ticklabels in a seaborn plot [duplicate]

This question already has answers here:
Modify tick label text
(13 answers)
Closed 5 months ago.
I am unable to set x axis ticklabels for a seaborn lineplot correctly.
import pandas as pd
import numpy as np
import seaborn as sns
import matplotlib.pyplot as plt
df = pd.DataFrame({'a':np.random.rand(8),'b':np.random.rand(8)})
sns.set(style="darkgrid")
g = sns.lineplot(data=df)
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])
The years on the x axis are not aligning properly.
Whenever you set the x-ticklabels manually, you should try to first set the corresponding ticks, and then specify the labels. In your case, therefore you should do
g = sns.lineplot(data=df)
g.set_xticks(range(len(df))) # <--- set the ticks first
g.set_xticklabels(['2011','2012','2013','2014','2015','2016','2017','2018'])
As of matplotlib 3.5.0
set_xticklabels is now discouraged:
The use of this method is discouraged because of the dependency on tick positions. In most cases, you'll want to use set_xticks(positions, labels) instead.
Now set_xticks includes a new labels param to set ticks and labels simultaneously:
ax = sns.lineplot(data=df)
ax.set_xticks(range(len(df)), labels=range(2011, 2019))
# ^^^^^^

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