Change legend position in ggplot2 using Python

In this tutorial, we will learn how to change the legend position in ggplot2 using Python. Some of you reading this article might start wondering how to even use ggplot2 in python. To answer this question in python, there are several packages that provide a grammar of graphics, but in this tutorial, we will focus on plotnine, which is based on ggplot2. If you have any experience in ggplot2 in R programming and then using ggplot2 using plotnine is very similar to it.

Changing legend position in ggplot2 using python

For this tutorial, I will use a google colab notebook, in which the plotnine package is preinstalled for us. If you want to use a Jupyter Notebook or your local environment, then just go ahead and install the required dependencies like plotnine, jupyter using pip. We will also import a popular dataset called mtcars(Motor Trend Car Road Tests) which comes with plotnine.

Let’s first import all the required dependencies in the google colab notebook

# importing dependencies
from plotnine import ggplot, aes, geom_point, labs, theme
import pandas as pd
# importing dataset
from plotnine.data import mtcars

Let’s learn more about the dataset using the info() method

mtcars.info()

Output:

<class 'pandas.core.frame.DataFrame'>
 RangeIndex: 12 entries, 0 to 11 
Data columns (total 12 columns): 
# Column Non-Null Count Dtype --- ------ -------------- ----- 
0 name 12 non-null object 
1 mpg 12 non-null float64 
2 cyl 12 non-null int64 
3 disp 12 non-null float64 
4 hp 12 non-null int64 
5 drat 12 non-null float64 
6 wt 12 non-null float64 
7 qsec 12 non-null float64 
8 vs 12 non-null int64 
9 am 12 non-null int64 
10 gear 12 non-null int64 
11 carb 12 non-null int64 
dtypes: float64(5), int64(6), object(1) 
memory usage: 1.2+ KB

Here we can see all the columns and their data types. Let’s pick only the first 12 rows for simplicity.

mtcars = mtcars.head(12)

Now let’s plot the graph

ggplot(mtcars) + aes(x='mpg', y='wt', color='name')+ labs(
        x="Miles/(US) gallon",
        y="Weight (1000 lbs)",
        color="Name of vehicle",
        title="Miles per Gallon vs Weight",
    ) + geom_point() + theme(legend_position='right')

Output:

Change legend position in ggplot2 using Python

Here ggplot(), aes() are used for plotting data by specifying which columns in the dataset should be plotted against in the graph. The labs() function is used to specify labels and titles for the graph, and geom_point() is used to create scatter plots. The theme() function with legend_position attribute specifies the legend position; in this case, I have given the value of the right, but by default, it will be the right. We can also give left, bottom, and top values in the legend_position attribute to change the position of the legend.

We can not only use top, bottom, right, and left values but also coordinates. Here assume the left bottom corner is (0,0) and the right top corner is (1,1). We can set these coordinates values in the legend_position attribute; for example, take a look at the below code.

ggplot(mtcars) + aes(x='mpg', y='wt', color='name')+ labs(
        x="Miles/(US) gallon",
        y="Weight (1000 lbs)",
        color="Name of vehicle",
        title="Miles per Gallon vs Weight",
    ) + geom_point() + theme(legend_position=[0.5,0.5])

Output:

ggplot()

Now we can see the legend is in the middle of the graph on top of it. This is not possible using the before method.

Leave a Reply

Your email address will not be published. Required fields are marked *