A ggplot question, but in Python! That's because you're using ggplot from the plotnine library, which is a Python implementation of the grammar of graphics (similar to R's ggplot2). To add a legend to your plot, you can map the color aesthetic to a variable within aes(), and then use scale_color_*() functions to customize the legend. Here's how you can modify your code to include a legend:
python
from plotnine import ggplot, geom_line, scale_color_manual
import pandas as pd
# Assuming plotdata is your DataFrame and 'years', 'USA', 'JPN', 'AUS' are your columns
# Melt the data to convert it into long format, which is more suitable for ggplot
# 'id_vars' specifies the column to keep unchanged ('years' in this case)
# 'value_vars' lists the columns to melt ('USA', 'JPN', 'AUS')
# 'var_name' sets the name of the new column for country names ('Country')
# 'value_name' sets the name of the new column for values ('Value')
plotdata_melted = pd.melt(plotdata, id_vars=['years'], value_vars=['USA', 'JPN', 'AUS'],
var_name='Country', value_name='Value')
# Now, plot with a legend
# Use aes() to map 'years' to x-axis, 'Value' to y-axis, and 'Country' to color
# geom_line() creates a line graph
# scale_color_manual() customizes the legend
ggplot(data=plotdata_melted, mapping=aes(x='years', y='Value', color='Country')) +
geom_line() +
scale_color_manual(
name="Country", # Sets the title of the legend
values=['blue', 'red', 'green'] # Specifies colors for each country
)
What Changed and Why:
Data Transformation: The data was transformed from wide to long format using pd.melt(). This is because ggplot (and its Python implementation plotnine) works more elegantly with data in long format when you want to create separate lines (or other geoms) based on a categorical variable (in this case, 'Country').
Mapping Color within aes(): By moving the color specification inside aes() and mapping it to 'Country', ggplot automatically generates a legend for the different countries.
scale_color_manual(): This function is used to specify the colors for each country. The name parameter is used to set the title of the legend, and values is a list of colors corresponding to each level of the 'Country' variable (in the order they appear in your data or as specified in limits if used within scale_color_manual()).
Tips:
Ensure the order and number of colors in scale_color_manual(values=...) match the countries in your data. If the countries' order is not as expected, consider specifying it with the limits argument within scale_color_manual().
For more customization options (e.g., legend position, labels), explore other scale_color_*() functions and theme() elements in plotnine.
You can adjust the position of the legend using theme(legend_position="bottom") or other valid positions ('left', 'right', 'top', 'none').
To change the labels in the legend, use scale_color_manual(labels=["United States", "Japan", "Australia"]) within scale_color_manual().