Removing label in Boxplot in Python - python

I'm unable to remove the label "Age" under each box plot shown below. Its autogenerated and can't get rid of it. Here is my code and output:
dataset.boxplot(column=['Age'], by=None, ax=None, fontsize=None, rot=0,
grid=True, figsize=None, layout=None, return_type=None)
plt.suptitle('Attrition by Age')
plt.xlabel('test')
plt.title('test6')
plt.subplot(121)
plt.xlabel('test2')
plt.title('test3')
plt.ylabel('test5')
enter image description here

This is because here "Age" is not an axis label, instead it is a tick. So you can add something like this:
plt.xticks([1], [''])
to remove the first tick.
And there are many other ways to remove or change ticks. For example, this post describes how to remove ticks on different axes.

Related

Countplot error: min() arg is an empty sequence

I have a problem where sns.countplot won't work. I got the names of the most popular color in each year, and with that I'm trying to plot a countplot that will show number (count) of each of those color. Something like .value_counts() but in a graph.
Here is the code that I've written:
most_popular_color = df_merged_full.groupby('year')[['name_cr_invp_inv']].agg({lambda color_name: color_name.value_counts().idxmax()}).reset_index()
and it returns this (example not full file):
Now when I try to do the countplot:
sns.countplot(most_popular_color['name_cr_invp_inv'],
palette={color: color for color in most_popular_color['name_cr_invp_inv'].drop_duplicates()})
it returns an error: min() arg is an empty sequence.
Where is the problem, I can't find it?
From the question, it looks like you are trying to plot the number of entries with each color and map the color to the bar. For this, you just need to provide a dictionary with mapping of each color to the column value (which will be the same in this case) and use that as the palette. I have used the data you provided above and created this. As white is one of the colors, I have added a border so that you can see the bar. Hope this is what you are looking for...
## Create dictionary with mapping of colors to the various unique entries in data
cmap = dict(zip(df_merged_full.name_cr_invp_inv.unique(), df_merged_full.name_cr_invp_inv.unique()))
fig, ax = plt.subplots() ## To add border, we will need ax
ax=sns.countplot(x=df_merged_full.name_cr_invp_inv, palette=cmap) ## Plot with pallette=cmap
plt.setp(ax.patches, linewidth=1, edgecolor='black') ## Add border

How to replace ticks in Matplotlib?

I would like to change the ticks intervals on a figure, which looks like that:
I use this:
plt.xticks(np.arange(1945, 2016, 10))
However, what I finally get is:
As you can see, I can't take out the smaller ticks. I tried this line:
ax.tick_params(axis='x', length=0)
But without success, since it show this:
I lost the ticks I would like to plot.
To plot, my code is:
for row, plot in enumerate(toplot):
for col, country in enumerate(countries):
ax = axes[row][col]
(dx[(plot, country)]
.plot(ax=ax, c=color)
)
Any idea?
It looks like what you want to do is disable the "minor ticks". Here you can find the official documentation about it, and another thread on stackoverflow about it. I did not try it myself bu just adding ax.minorticks_off() should do the trick !

Seaborn catplot + barplot : extra axis

I use Seaborn/Matplotlib to display different outputs (time and distance for example) for different parameters. I would like to associate the two outputs on the same plot, thus I use seaborn's satplot and barplot.
My problem is I don't get the expected display. The graph is here but some noisy extra axis appear.
I'm running the following code
ax = plt.subplot(311)
ax2 = ax.twinx()
data = sns.load_dataset("tips")
sns.barplot(ax=ax, x="day",y="total_bill", hue="size" , data=data, ci=None)
ax.set_yscale("log")
sns.catplot(data=data, x="day", y="tip", ax=ax2, hue="size", kind="swarm", palette="bright")
And I have the following result :
Could you help me to remove this extra axis ? It is especially inconvenient when having multiple subplots.
The extra axis you see is the one returned by the catplot. To get rid of it, you can add the following line after the sns.catplot(...) where the index 2 refers to the count of the figure.
plt.close(2)
To test that, if you use plt.close(1), it will remove the main figure containing bar chart
The extra axes you see is the catplot you create. catplot is a figure-level function (i.e. it creates its own figure); and hence does not really have an ax argument. One could see it as bug that it still allows for it. What you would probably like to do is to create a sns.swarmplot instead, which does have the ax argument.

Remove axes in matplotlib subplots?

I've got a pandas dataframe with 4 columns and a date range as the index. After showing the trend lines on four subplots using this code, I realized I don't want the y axis ticks or labels, but I can't find any advice on removing them from the subplots; everything I try only works on the bottom plot.
plot4 = CZBCdf2.plot(subplots=True,figsize=(10,4),sharex=True)
The typical way of removing axis in matplotlib is:
import matplotlib.pyplot as plt
plt.axis('off')
This, however, is a general instruction in matplotlib. To set the axis to invisible you can do (using a subplot):
ax.xaxis.set_visible(False) # same for y axis.
You seem to be calling the plot from other source. If this instructions don't do the stuff you need provide more of your code to see what might be the procedure to achieve that.
A complete solution to remove anything around the plot
figure, axis = plt.subplots(1, figsize=[10,3])
axis.plot(...)
axis.xaxis.set_visible(False)
axis.yaxis.set_visible(False)
for spine in ['top', 'right', 'left', 'bottom']:
axis.spines[spine].set_visible(False)
figure.savefig('demo.png', bbox_inches='tight', transparent="True", pad_inches=0, )
Set yticks=[]
So, in your example:
plot4 = CZBCdf2.plot(subplots=True,figsize=(10,4),sharex=True, yticks=[])

Labels for scatterplot-matrices

I have been trying to plot a scatterplot matrix using the great example given by Joe Kington:
However, I would like to add xlabels and ylabels on the subplots where I have displayed ticks. When you change the positions of the ticks, the associated x/ylabel does not follow.
I have not been able to find an option to change the location of the label; I was hoping to find something like ax.set_xlabel('XLabel',position='top') but it does not exist.
This is what I get finally,
For example I would like X axis4 to be above the ticks.
If you want to change the x-label from bottom to top, or the y-label from left to right, you can (provided the specific suplot is called ax) do it by calling:
ax.xaxis.set_label_position('top')
ax.yaxis.set_label_position('right')
If you for example want the label "X label 2" to stay where it is but don't overlap the other subplot, you can try to add a
fig.tight_layout()
just before the fig.show().

Categories

Resources