Rotating both subplots x ticks [duplicate] - for-loop

I am trying to rotate the x axis labels for every subplot. Here is my code:
fig.set_figheight(10)
fig.set_figwidth(20)
ax.set_xticklabels(dr_2012['State/UT'], rotation = 90)
ax[0, 0].bar(dr_2012['State/UT'], dr_2012['Primary Total'])
ax[0, 0].set_title('Dropout Ratios 2012-2013 (Primary)')
ax[0, 1].bar(dr_2012['State/UT'], dr_2012['Upper Primary Total'])
ax[0, 1].set_title('Dropout Ratios 2012-2013 (Upper Primary)')
ax[1, 0].bar(dr_2012['State/UT'], dr_2012['Secondary Total'])
ax[1, 0].set_title('Dropout Ratios 2012-2013 (Secondary)')
ax[1, 1].bar(dr_2012['State/UT'], dr_2012['HS Total'])
ax[1, 1].set_title('Dropout Ratios 2012-2013 (HS)')
subplot
None of the usual things seem to work for me. I have tried ax.set_xticklabels and ax.tick_params. I have also tried looping through the ticks using ax.get_xticklabels and even that didn't work. It always gave me this error -
AttributeError: 'numpy.ndarray' object has no attribute 'set_xticklabels'/'get_xticklabels'/'tick_params'
I am at a loss. Why wouldn't it be working?

Use tick_params on the AxesSubplot, but ax in your case is an np array of AxesSubplot objects.
Fix
ax[1][0].tick_params(axis='x', rotation=90)
Sample usage
import matplotlib.pyplot as plt
fig,ax = plt.subplots(2,2)
import numpy as np
x = np.arange(1,5)
ax[0][0].plot(x,x*x)
ax[0][0].set_title('square')
ax[0][0].tick_params(axis='x', rotation=90)
ax[0][1].plot(x,np.sqrt(x))
ax[0][1].set_title('square root')
ax[0][1].tick_params(axis='x', rotation=90)
ax[1][0].plot(x,np.exp(x))
ax[1][0].set_title('exp')
ax[1][0].tick_params(axis='x', rotation=90)
ax[1][1].plot(x,np.log10(x))
ax[1][1].set_title('log')
ax[1][1].tick_params(axis='x', rotation=90)
plt.show()
Output:

Related

Is there any way to change the legends in seaborn?

I would like to change the format of pIC50 in the legend box. I would like it to be "circle according to the size with no filled color". Any suggestions are welcome!
plt.figure(figsize=(7, 7))
sns.scatterplot(x='MW', y='LogP', data=df_2class, hue='class', size='pIC50', edgecolor='black', alpha=0.2)
sns.set_style("whitegrid", {"ytick.major.size": 100,"xtick.major.size": 2, 'grid.linestyle': 'solid'})
plt.xlabel('MW', fontsize=14, fontweight='bold')
plt.ylabel('LogP', fontsize=14, fontweight='bold')
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0)
In this case, you can loop through the last legend handles and change the color of the dots. Here is an example using the iris dataset:
import matplotlib.pyplot as plt
import seaborn as sns
iris = sns.load_dataset('iris')
ax = sns.scatterplot(data=iris, x='sepal_length', y='petal_length', hue='species', size='sepal_width')
handles, labels = ax.get_legend_handles_labels()
for h in handles[-5:]: # changes the 5 last handles, this number might be different in your case
h.set_facecolor('none')
ax.legend(handles=handles, labels=labels, bbox_to_anchor=[1.02, 1.02], loc='upper left')
plt.tight_layout()
plt.show()

GDF.simplify messes up geometries

I am trying to plot river basins on a map. In order to reduce the size of the resulting vector graphics, I am applying GeoSeries.simplify().
import cartopy
import cartopy.crs as ccrs
import matplotlib.pyplot as plt
import geopandas as gpd
# %%% Earth
fig = plt.figure()
latlon_proj = ccrs.PlateCarree()
axis_proj = ccrs.Orthographic()
ax = plt.axes(
projection=axis_proj
)
# %%% Major River Basins
mrb_basins = gpd.read_file('mrb_basins.json') # 520 entries
mrb_basins['geometry'] = mrb_basins['geometry'].simplify(0.1)
for shape in mrb_basins['geometry']:
feat = cartopy.feature.ShapelyFeature(
[shape],
latlon_proj,
facecolor='red',
)
ax.add_feature(feat)
mrb_basins.plot()
The problem is, the resulting map of the earth is fully covered by a red shape.
This is not the case, if I remove the line mrb_basins['geometry'] = mrb_basins['geometry'].simplify(0.1).
How can I simplify the geometries whilst keeping their integrity?
The data set of major river basins is available here.
GeoSeries.simplify() does not always return valid geometries due to the underlying simplification algorithm used by GEOS. And cartopy has trouble to plot invalid geometries.
You need to fix your geometries before passing them to cartopy. The simple trick is to call buffer(0).
mrb_basins['geometry'] = mrb_basins['geometry'].simplify(0.1).buffer(0)
Then your code works fine.

How do I get rid of space between x-ticks and axis in Seaborn heatmap?

In a Seaborn heatmap (within Jupyter Notebook), I am getting extra space between the axis and the x-ticks, which I've moved to the top. If I leave the ticks at the bottom, they are flush as expected, but I need them at the top. I can't figure how to get rid of that space between the upper edge of the plot and the x-ticks. I tried the padding setting in set_tick_params, but that only adjusts space between the tick and the label.
Here's a subset of the data to play with
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sb
axis_labels = ['Q1','Q2','Q3','Q4','Q5']
data = pd.DataFrame([[np.nan,0.14,0.01,0.00,-0.05],
[0.30,np.nan,0.01,0.03,-0.04],
[0.16,0.10,np.nan,0.01,-0.02],
[0.14,0.05,0.02,np.nan,-0.04],
[0.16,0.09,0.01,0.02,np.nan]])
fig, ax = plt.subplots(figsize=(15,15))
sb.heatmap(data, ax=ax, center=0, annot=True, mask=data.isnull(),
square=True, cmap=sb.diverging_palette(275, 150, s=80, l=55, as_cmap=True), cbar_kws={"shrink": 0.75})
ax.set_ylim(5,-0.5)
ax.set_xticklabels(axis_labels, rotation=90, ha='center', fontsize=12)
ax.set_yticklabels(axis_labels, rotation=0, fontsize=12)
ax.xaxis.tick_top();
Probably something super simple that I'm missing. Any ideas?

How to rotate ylabel of pairplot in searborn? [duplicate]

I have a simple factorplot
import seaborn as sns
g = sns.factorplot("name", "miss_ratio", "policy", dodge=.2,
linestyles=["none", "none", "none", "none"], data=df[df["level"] == 2])
The problem is that the x labels all run together, making them unreadable. How do you rotate the text so that the labels are readable?
I had a problem with the answer by #mwaskorn, namely that
g.set_xticklabels(rotation=30)
fails, because this also requires the labels. A bit easier than the answer by #Aman is to just add
plt.xticks(rotation=45)
You can rotate tick labels with the tick_params method on matplotlib Axes objects. To provide a specific example:
ax.tick_params(axis='x', rotation=90)
This is still a matplotlib object. Try this:
# <your code here>
locs, labels = plt.xticks()
plt.setp(labels, rotation=45)
Any seaborn plots suported by facetgrid won't work with (e.g. catplot)
g.set_xticklabels(rotation=30)
however barplot, countplot, etc. will work as they are not supported by facetgrid. Below will work for them.
g.set_xticklabels(g.get_xticklabels(), rotation=30)
Also, in case you have 2 graphs overlayed on top of each other, try set_xticklabels on graph which supports it.
If anyone wonders how to this for clustermap CorrGrids (part of a given seaborn example):
import seaborn as sns
import matplotlib.pyplot as plt
sns.set(context="paper", font="monospace")
# Load the datset of correlations between cortical brain networks
df = sns.load_dataset("brain_networks", header=[0, 1, 2], index_col=0)
corrmat = df.corr()
# Set up the matplotlib figure
f, ax = plt.subplots(figsize=(12, 9))
# Draw the heatmap using seaborn
g=sns.clustermap(corrmat, vmax=.8, square=True)
rotation = 90
for i, ax in enumerate(g.fig.axes): ## getting all axes of the fig object
ax.set_xticklabels(ax.get_xticklabels(), rotation = rotation)
g.fig.show()
You can also use plt.setp as follows:
import matplotlib.pyplot as plt
import seaborn as sns
plot=sns.barplot(data=df, x=" ", y=" ")
plt.setp(plot.get_xticklabels(), rotation=90)
to rotate the labels 90 degrees.
For a seaborn.heatmap, you can rotate these using (based on #Aman's answer)
pandas_frame = pd.DataFrame(data, index=names, columns=names)
heatmap = seaborn.heatmap(pandas_frame)
loc, labels = plt.xticks()
heatmap.set_xticklabels(labels, rotation=45)
heatmap.set_yticklabels(labels[::-1], rotation=45) # reversed order for y
One can do this with matplotlib.pyplot.xticks
import matplotlib.pyplot as plt
plt.xticks(rotation = 'vertical')
# Or use degrees explicitly
degrees = 70 # Adjust according to one's preferences/needs
plt.xticks(rotation=degrees)
Here one can see an example of how it works.
Use ax.tick_params(labelrotation=45). You can apply this to the axes figure from the plot without having to provide labels. This is an alternative to using the FacetGrid if that's not the path you want to take.
If the labels have long names it may be hard to get it right. A solution that worked well for me using catplot was:
import matplotlib.pyplot as plt
fig = plt.gcf()
fig.autofmt_xdate()

In Matplotlib, how do you add an Imagedraw object to a PyPlot?

I need to add a shape to a preexisting image generated using a pyplot (plt). The best way I know of to generate basic shapes quickly is using Imagedraw's predefined shapes. The original data has points with corresponding colors in line_holder and colorholder. I need to add a bounding box (or in this case ellipse) to the plot to make it obvious to the user whether the data is in an acceptable range.
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from PIL import Image
...
lines = LineCollection(mpl.line_holder, colors=mpl.colorholder , linestyle='solid')
plt.axes().add_collection(lines)
plt.axes().set_aspect('equal', 'datalim')
plt.axes().autoscale_view(True,True,True)
plt.draw()
plt.show()
I tried inserting this before the show():
image = Image.new('1',(int(ceil(disc/conv))+2,int(ceil(disc/conv))+1), 1)
draw = ImageDraw.Draw(image)
box=(1, 1, int(ceil(disc/conv)), int(ceil(disc/conv))) #create bounding box
draw.ellipse(box, 1, 0) #draw circle in black
but I cannot find a way to then add this ellipse to the pyplot. Does anyone know how one would go about getting the images together? If it is not possible to add an imagedraw object to a pyplot, are there good alternatives for performing this type of operation?
Matplotlib has several patches (shapes) that appear to meet your needs (and remove PIL as a dependency). They are documented here. A helpful example using shapes is here.
To add an ellipse to a plot, you first create a Ellipse patch and then add that patch to the axes you're currently working on. Beware that Circle's (or Ellipse's with equal minor radii) will appear elliptical if your aspect ratio is not equal.
In your snippet you call plt.axes() several times. This is unnecessary, as it is just returning the current axes object. I think it is clearer to keep the axes object and directly operate on it rather than repeatedly getting the same object via plt.axes(). As far as axes() is used in your snippet, gca() does the same thing. The end of my script demonstrates this.
I've also replaced your add_collection() line by a plotting a single line. These essentially do the same thing and allows my snippet to be executed as a standalone script.
import matplotlib.pyplot as plt
import matplotlib as mpl
# set up your axes object
ax = plt.axes()
ax.set_aspect('equal', 'datalim')
ax.autoscale_view(True, True, True)
# adding a LineCollection is equivalent to plotting a line
# this will run as a stand alone script
x = range(10)
plt.plot( x, x, 'x-')
# add and ellipse to the axes
c = mpl.patches.Ellipse( (5, 5), 1, 6, angle=45)
ax.add_patch(c)
# you can get the current axes a few ways
ax2 = plt.axes()
c2 = mpl.patches.Ellipse( (7, 7), 1, 6, angle=-45, color='green')
ax2.add_patch(c2)
ax3 = plt.gca()
c3 = mpl.patches.Ellipse( (0, 2), 3, 3, color='black')
ax3.add_patch(c3)
print id(ax), id(ax2), id(ax3)
plt.show()

Resources