Edit labels and move legend in seaborn [duplicate] - seaborn

This question already has answers here:
Edit legend title and labels of Seaborn scatterplot and countplot
(3 answers)
How to edit a seaborn legend title and labels for figure-level functions
(2 answers)
How to customize seaborn.scatterplot legends?
(1 answer)
Closed 7 months ago.
I have a seaborn scatterplot, which I want to change its labels and move the legend outside the graph. There are many solutions to fix each of the issues, but I cannot fix both of them simultaneously. Adapted from a solution in stackoverflow which was intended for sns.lmplot:
import seaborn as sns
import matplotlib.pyplot as plt
tips = sns.load_dataset("tips")
g = sns.scatterplot(x="total_bill", y="tip", hue="smoker", data=tips, legend=False)
plt.legend(title='Smoker', bbox_to_anchor=(1.05, 1), labels=['Hell Yeh', 'Nah Bruh'])
plt.show(g)
Here legend=False and is defined later by matplotlib. The issue is the plot only displays the first label and not the rest in the legend.
I have tried another way to modify the label by legend='full' and later modifying it:
g = sns.scatterplot(x="total_bill", y="tip", hue="smoker", data=tips, legend='full')
h,l = g.get_legend_handles_labels()
l = ['Smoking behaviors:','Hell Yeh', 'Nah Bruh']
g.legend(h, l)
but the command g.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)does not work properly and edited labels do not show up. Only original labels are shown.
So, I can fix both of these issues separately, but not at the same time.

In the current version of Seaborn's scatterplot (0.11.1), you can first create the legend in full and afterwards change it by calling ax.legend() again.
Note that the return value of sns.scatterplot is an ax as it is an axes-level function. This should not be confused with figure level functions which return a complete grid of "axes" and often are written as g = sns....
Different seaborn functions create legends in different ways. Depending on the options used, the legend can become quite intricate and not easy to change. Making legends easier to modify is planned in Seaborn's future developments.
from matplotlib import pyplot as plt
import seaborn as sns
tips = sns.load_dataset('tips')
ax = sns.scatterplot(x="total_bill", y="tip", hue="smoker", data=tips, legend='full')
ax.legend(title='Smoker', bbox_to_anchor=(1.05, 1), labels=['Hell Yeh', 'Nah Bruh'])
plt.tight_layout()
plt.show()

Related

Why is the first subplot skipped? [duplicate]

This question already has an answer here:
seaborn is not plotting within defined subplots
(1 answer)
Closed 7 months ago.
I was trying to create visualize a variable using sns.distplot() and sns.boxplot()
the code
I got this result:
result
Apparently,first subplot is skipped.Does anyone know why this is happening?
The reason you are seeing the displot outside is because it is a figure-level function and you cannot use ax in it. You can change it to histplot and should see it working...
fig, axes = plt.subplots(2,1,figsize=(5,5))
sns.histplot(wine['fixed acidity'], ax=axes[0])
sns.boxplot(wine['fixed acidity'], ax=axes[1])
Plot

Changing size parameters in seaborn without any success

Here is the code:
import seaborn as sns
tips = sns.load_dataset("tips")
p1 = sns.countplot(x='sex',data=tips)
No matter what size adjustments I try to make by adding the height parameter or aspect, this is how it appears in Jupyter. Any idea how to change this? I am following a tutorial and in the video tutorial it appears fine, just not for me.

Zooming out on pandas table in Jupyter Notebooks

I am attempting to take a screenshot of a correlation table made with pandas in Jupyter Notebooks but since it is very wide I must scroll to the right in order to view the whole table. On a mac it is not possible to scroll left or right while taking a screenshot so I am unable to capture the entire table. Is there anyway to get the entire table (doesn't have to be a screenshot an export of some type would work as well)?
Is the table already shown in markdown? If not, you can try df.to_html(). From there, you can convert it to pdf, see (https://www.npmjs.com/package/markdown-pdf)
Otherwise you can plot the pandas table with matplotlib and remove the axis etc.
import matplotlib.pyplot as plt
import pandas as pd
from pandas.table.plotting import table
ax = plt.subplot(111, frame_on=False) # no visible frame
ax.xaxis.set_visible(False) # hide the x axis
ax.yaxis.set_visible(False) # hide the y axis
table(ax, df) # where df is your data frame
plt.savefig('table.png')

Choropleth map from Shape file in Holoviews

I have a shape file with a column named geometry containing MULTIPOLYGONs.
postcode name geometry
0 2003.0 A MULTIPOLYGON Z (((1048559.000 7841160.000 0.00...
1 1438.0 B MULTIPOLYGON Z (((-29156.720 6885495.170 0.000...
While it is straight forward to draw a map in matplotlib with GeoPandas, I can not get it to work in Holoviews. The example-script from Holoviews (http://holoviews.org/gallery/demos/bokeh/texas_choropleth_example.html) don't really solve the question of how to structure the data.
I have tried to read the shape file with GeoPandas without luck. What am I missing here? Do I need to decode the geometry column first?
If you install hvPlot, you should be able to plot shape columns directly from GeoPandas using HoloViews, as described at https://hvplot.holoviz.org/user_guide/Geographic_Data.html .
import hvplot.pandas, geopandas as gpd
world = gpd.read_file(gpd.datasets.get_path('naturalearth_lowres'))
world.hvplot(geo=True)

trellis layered plots in altair/Vega-Lite

I would like to compare multiple conditions of an altair (ultimately vega-lite) layered plot. The perfect solution would be to facet/trellis the plot so I can see the different conditions side by side. Unfortunately I cannot figure out how to give the command to plot the different conditions.
Here is my attempt to implement my idea based on the example for layered plots:
(https://github.com/ellisonbg/altair/blob/master/altair/notebooks/07-LayeredCharts.ipynb)
import pandas as pd
import numpy as np
data = pd.DataFrame({'x':np.random.rand(10), 'y':np.random.rand(10), 'z':['a', 'b']*5})
chart = LayeredChart(data)
chart += Chart().mark_line().encode(x='x:Q', y='y:Q', column='z:Q')
chart += Chart().mark_point().encode(x='x:Q', y='y:Q', column='z:Q')
chart
When compared with the example I added the column 'z' with the two conditions, and the two column statements in the Chart definitions.
This solution generates seemingly good Vega-lite code, but no plot. Alternatively I tried "chart = LayeredChart(data).encode(column='z:Q')" but I then got the error 'LayeredChart' object has no attribute 'encode'
I am wondering whether it is possible to facet (trellis) layered plots at all and whether it will be possible in future Vega-Lite releases.
I am using jupyter with Anaconda
Layering is only experimentally supported in the current release of Vega-Lite and Altair, and I believe you've hit one of the unsupported aspects. This should be addressed in the Vega-Lite 2.0 release (and associated Altair release) later this spring.

Resources