I have a pairplot in Python. I like to add x-axis and y-axis ticks (i.e, numbers) to all boxes. So, the ticks and their labels at the bottom and left side of pairplot will repeat for each box. See the below pictures.
Thanks in advance!
What I have
what I want to have
You can set ax.tick_params() and adjust the subplot spacing.
import matplotlib.pyplot as plt
import seaborn as sns
penguins = sns.load_dataset("penguins")
pp = sns.pairplot(
penguins,
x_vars=["bill_length_mm", "bill_depth_mm", "flipper_length_mm"],
y_vars=["bill_length_mm", "bill_depth_mm"],
)
for ax in pp.axes.flat:
ax.tick_params(axis='both', labelleft=True, labelbottom=True)
plt.subplots_adjust(wspace=0.3, hspace=0.3)
plt.show()
Related
I have a semilogx plot and I would like to remove the xticks. I tried:
plt.gca().set_xticks([])
plt.xticks([])
ax.set_xticks([])
The grid disappears (ok), but small ticks (at the place of the main ticks) remain. How to remove them?
The plt.tick_params method is very useful for stuff like this. This code turns off major and minor ticks and removes the labels from the x-axis.
Note that there is also ax.tick_params for matplotlib.axes.Axes objects.
from matplotlib import pyplot as plt
plt.plot(range(10))
plt.tick_params(
axis='x', # changes apply to the x-axis
which='both', # both major and minor ticks are affected
bottom=False, # ticks along the bottom edge are off
top=False, # ticks along the top edge are off
labelbottom=False) # labels along the bottom edge are off
plt.show()
plt.savefig('plot')
plt.clf()
Not exactly what the OP was asking for, but a simple way to disable all axes lines, ticks and labels is to simply call:
plt.axis('off')
Alternatively, you can pass an empty tick position and label as
# for matplotlib.pyplot
# ---------------------
plt.xticks([], [])
# for axis object
# ---------------
# from Anakhand May 5 at 13:08
# for major ticks
ax.set_xticks([])
# for minor ticks
ax.set_xticks([], minor=True)
Here is an alternative solution that I found on the matplotlib mailing list:
import matplotlib.pylab as plt
x = range(1000)
ax = plt.axes()
ax.semilogx(x, x)
ax.xaxis.set_ticks_position('none')
There is a better, and simpler, solution than the one given by John Vinyard. Use NullLocator:
import matplotlib.pyplot as plt
plt.plot(range(10))
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.show()
plt.savefig('plot')
Try this to remove the labels (but not the ticks):
import matplotlib.pyplot as plt
plt.setp( ax.get_xticklabels(), visible=False)
example
This snippet might help in removing the xticks only.
from matplotlib import pyplot as plt
plt.xticks([])
This snippet might help in removing the xticks and yticks both.
from matplotlib import pyplot as plt
plt.xticks([]),plt.yticks([])
Those of you looking for a short command to switch off all ticks and labels should be fine with
plt.tick_params(top=False, bottom=False, left=False, right=False,
labelleft=False, labelbottom=False)
which allows type bool for respective parameters since version matplotlib>=2.1.1
For custom tick settings, the docs are helpful:
https://matplotlib.org/api/_as_gen/matplotlib.axes.Axes.tick_params.html
# remove all the ticks (both axes), and tick labels on the Y axis
plt.tick_params(top='off', bottom='off', left='off', right='off', labelleft='off', labelbottom='on')
Modify the following rc parameters by adding the commands to the script:
plt.rcParams['xtick.bottom'] = False
plt.rcParams['xtick.labelbottom'] = False
A sample matplotlibrc file is depicted in this section of the matplotlib documentation, which lists many other parameters like changing figure size, color of figure, animation settings, etc.
A simple solution to this problem is to set the color of the xticks to White or to whatever the background color is. This will hide the text of the xticks but not the xticks itself.
import matplotlib.pyplot as plt
plt.plot()
plt.xticks(color='white')
plt.show()
Result
I am trying to make a line plot using seaborn and in the image link I have attached
it seems like it did not show the required dates (daily) in the x-axis. How can I fix this chart?
%matplotlib inline
import matplotlib as mpl
import matplotlib.pyplot as plt
mpl.style.use(['ggplot'])
import seaborn as sns
sns.set_style("whitegrid")
fig, g = plt.subplots(figsize = (20,6))
g = sns.lineplot(x="photosim_date", y="tdpower_mean", hue="tool_id", style="tool_id", data=df1, dashes=False, ax=g)
plt.ylim(80,140)
plt.title("L8 PhotoSIM SDET TDP Data")
plt.show(g)
You can change the x-axis tick locator.
loc = matplotlib.dates.DayLocator(bymonthday=range(1,32))
ax.xaxis.set_major_locator(loc)
Be wary that the axis labels will most likely overlap in this case. You can use fig.autofmt_xdate() to automatically rotate the labels.
I would like to minimize white space in my figure. I have a row of sub plots where four plots share their y-axis and the last plot has a separate axis.
There are no ylabels or ticklabels for the shared axis middle panels.
tight_layout creates a lot of white space between the the middle plots as if leaving space for tick labels and ylabels but I would rather stretch the sub plots. Is this possible?
import matplotlib.gridspec as gridspec
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
fig = plt.figure()
gs = gridspec.GridSpec(1, 5, width_ratios=[4,1,4,1,2])
ax = fig.add_subplot(gs[0])
axes = [ax] + [fig.add_subplot(gs[i], sharey=ax) for i in range(1, 4)]
axes[0].plot(np.random.randint(0,100,100))
barlist=axes[1].bar([1,2],[1,20])
axes[2].plot(np.random.randint(0,100,100))
barlist=axes[3].bar([1,2],[1,20])
axes[0].set_ylabel('data')
axes.append(fig.add_subplot(gs[4]))
axes[4].plot(np.random.randint(0,5,100))
axes[4].set_ylabel('other data')
for ax in axes[1:4]:
plt.setp(ax.get_yticklabels(), visible=False)
sns.despine();
plt.tight_layout(pad=0, w_pad=0, h_pad=0);
Setting w_pad = 0 is not changing the default settings of tight_layout. You need to set something like w_pad = -2. Which produces the following figure:
You could go further, to say -3 but then you would start to get some overlap with your last plot.
Another way could be to remove plt.tight_layout() and set the boundaries yourself using
plt.subplots_adjust(left=0.065, right=0.97, top=0.96, bottom=0.065, wspace=0.14)
Though this can be a bit of a trial and error process.
Edit
A nice looking graph can be achieved by moving the ticks and the labels of the last plot to the right hand side. This answer shows you can do this by using:
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
So for your example:
axes[4].yaxis.tick_right()
axes[4].yaxis.set_label_position("right")
In addition, you need to remove sns.despine(). Finally, there is now no need to set w_pad = -2, just use plt.tight_layout(pad=0, w_pad=0, h_pad=0)
Using this creates the following figure:
I am trying to plot the below dataset as barplot cum pointplot using seaborn.
But the time-stamp in the x-axis labels shows additional zeroes at the end as shown below
The code I use is
import matplotlib.pyplot as plt
import seaborn as sns
fig, ax1 = plt.subplots()
# Plot the barplot
sns.barplot(x='Date', y=y_value, hue='Sentiment', data=mergedData1, ax=ax1)
# Assign y axis label for bar plot
ax1.set_ylabel('No of Feeds')
# Position the legen on the right side outside the box
plt.legend(loc=2, bbox_to_anchor=(1.1, 1), ncol=1)
# Create a dual axis
ax2 = ax1.twinx()
# Plot the ponitplot
sns.pointplot(x='Date', y='meanTRP', data=mergedData1, ax=ax2, color='r')
# Assign y axis label for point plot
ax2.set_ylabel('TRP')
# Hide the grid for secondary axis
ax2.grid(False)
# Give a chart title
plt.title(source+' Social Media Feeds & TRP for the show '+show)
# Automatically align the x axis labels
fig.autofmt_xdate()
fig.tight_layout()
Not sure what is going wrong. Please help me with this. Thanks
Easiest solution is to split the text at the letter "T" as the rest is probably not needed.
ax.set_xticklabels([t.get_text().split("T")[0] for t in ax.get_xticklabels()])
You can still have more control over date format with this code:
ax.set_xticklabels([pd.to_datetime(tm).strftime('%d-%m-%Y') for tm in ax.get_xticklabels()])
For the plot
sns.countplot(x="HostRamSize",data=df)
I got the following graph with x-axis label mixing together, how do I avoid this? Should I change the size of the graph to solve this problem?
Having a Series ds like this
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np; np.random.seed(136)
l = "1234567890123"
categories = [ l[i:i+5]+" - "+l[i+1:i+6] for i in range(6)]
x = np.random.choice(categories, size=1000,
p=np.diff(np.array([0,0.7,2.8,6.5,8.5,9.3,10])/10.))
ds = pd.Series({"Column" : x})
there are several options to make the axis labels more readable.
Change figure size
plt.figure(figsize=(8,4)) # this creates a figure 8 inch wide, 4 inch high
sns.countplot(x="Column", data=ds)
plt.show()
Rotate the ticklabels
ax = sns.countplot(x="Column", data=ds)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right")
plt.tight_layout()
plt.show()
Decrease Fontsize
ax = sns.countplot(x="Column", data=ds)
ax.set_xticklabels(ax.get_xticklabels(), fontsize=7)
plt.tight_layout()
plt.show()
Of course any combination of those would work equally well.
Setting rcParams
The figure size and the xlabel fontsize can be set globally using rcParams
plt.rcParams["figure.figsize"] = (8, 4)
plt.rcParams["xtick.labelsize"] = 7
This might be useful to put on top of a juypter notebook such that those settings apply for any figure generated within. Unfortunately rotating the xticklabels is not possible using rcParams.
I guess it's worth noting that the same strategies would naturally also apply for seaborn barplot, matplotlib bar plot or pandas.bar.
You can rotate the x_labels and increase their font size using the xticks methods of pandas.pyplot.
For Example:
import matplotlib.pyplot as plt
plt.figure(figsize=(10,5))
chart = sns.countplot(x="HostRamSize",data=df)
plt.xticks(
rotation=45,
horizontalalignment='right',
fontweight='light',
fontsize='x-large'
)
For more such modifications you can refer this link:
Drawing from Data
If you just want to make sure xticks labels are not squeezed together, you can set a proper fig size and try fig.autofmt_xdate().
This function will automatically align and rotate the labels.
plt.figure(figsize=(15,10)) #adjust the size of plot
ax=sns.countplot(x=df['Location'],data=df,hue='label',palette='mako')
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right") #it will rotate text on x axis
plt.tight_layout()
plt.show()
you can try this code & change size & rotation according to your need.
I don't know whether it is an option for you but maybe turning the graphic could be a solution (instead of plotting on x=, do it on y=), such that:
sns.countplot(y="HostRamSize",data=df)