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

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))
# ^^^^^^

Related

Is it possible to remove the empty side of the scatter plot matrix? [duplicate]

This question already has answers here:
Plot lower triangle in a seaborn Pairgrid
(2 answers)
Closed 5 days ago.
I would like to remove the 6 empty boxes on the top right side of the plot(pls see the figure marked in red). I tried few different arguments and it didn't work.
Here is the code I used.
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
# Example dataset
iris = sns.load_dataset("iris")
# Create PairGrid object with subplots
g = sns.PairGrid(iris, height=1.5, aspect=1.2)
# Create scatter plots on the lower side
g.map_lower(sns.scatterplot)
# Add regression line
g.map_lower(sns.regplot)
# Add histograms
g.map_diag(sns.histplot, kde=True)
# Then include correlation values for each scatter plot.
for i, j in zip(*plt.np.triu_indices_from(g.axes, k=1)):
corr_coef = plt.np.corrcoef(iris.iloc[:, i], iris.iloc[:, j])[0][1]
g.axes[j, i].annotate(f"R = {corr_coef:.2f}", xy=(.1, .9), xycoords=g.axes[j, i].transAxes)
plt.show()
You can use corner argument like this:
g = sns.PairGrid(iris, height=1.5, aspect=1.2, corner=True)
Result:

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

Seaborn - remove spacing from DataFrame histogram [duplicate]

This question already has answers here:
How can I change the x axis in matplotlib so there is no white space?
(2 answers)
Closed 5 years ago.
I am trying to generate a histogram from a DataFrame with seaborn enabled via the DataFrame.hist method, but I keep finding extra space added to either side of the histogram itself, as seen by the red arrows in the below picture:
How can I remove these spaces? Code to reproduce this graph is as follows:
import seaborn as sns
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from random import seed, choice
seed(0)
df = pd.DataFrame([choice(range(250)) for _ in range(100)], columns=['Values'])
bins = np.arange(0, 260, 10)
df['Values'].hist(bins=bins)
plt.tight_layout()
plt.show()
plt.tight_layout() only has an effect for the "outer margins" of your plot (tick marks, ax labels etc.).
By default matplotlib's hist leaves an inner margin around the hist bar-plot. To disable you can do this:
ax = df['Values'].hist(bins=bins)
ax.margins(x=0)
plt.show()

How to set ax.legend fontsize? [duplicate]

This question already has answers here:
How to change legend fontsize with matplotlib.pyplot
(9 answers)
Closed 6 years ago.
Here is my code
import os,sys
import Image
import matplotlib.pyplot as plt
from matplotlib.pyplot import *
from matplotlib.font_manager import FontProperties
jpgfile = Image.open("t002.jpg")
# Set up the figure and axes.
fig = plt.figure(figsize=(18,10)) # ...or whatever size you want.
ax = fig.add_subplot(111)
ax.legend(fontsize=18)
# Draw things.
plt.imshow(jpgfile) # Unlike plot and scatter, not a method on ax.
ax.set_xlabel('normalized resistivities')
ax.set_ylabel('normalized velocities')
ax.set_xticks([]); ax.set_yticks([])
# Save and show.
plt.savefig("fig.jpg")
plt.show()
But
/usr/local/lib/python2.7/dist-packages/matplotlib/axes/_axes.py:519: UserWarning: No labelled objects found. Use label='...' kwarg on individual plots
How should I set the labels?
Legend fonts are customized by providing a dict of font property-value pairs to the 'prop' kwarg:
ax.legend(prop=dict(size=18))

Categories

Resources