plot a seaborn lineplot and pick a color pallete such that certain years will look lighter and the current year will be highlighted in python

To plot a seaborn line plot with a custom color palette and highlight the current year, you can follow these steps:

  1. Import the necessary libraries:
main.py
import seaborn as sns
import matplotlib.pyplot as plt
54 chars
3 lines
  1. Prepare your data in a pandas DataFrame. Let's assume you have a DataFrame named df with two columns: year and value.

  2. Define a custom color palette using seaborn's light_palette() function:

main.py
palette = sns.light_palette("blue", n_colors=len(df["year"].unique()), reverse=True)
85 chars
2 lines

This will create a palette of lighter blue shades, with the number of colors equal to the number of unique years in your data.

  1. Plot the line plot and pass the palette as the color parameter to the lineplot() function. Additionally, you can use the hue parameter to distinguish different years visually:
main.py
sns.lineplot(data=df, x="year", y="value", hue="year", palette=palette)
72 chars
2 lines
  1. Set the current year as the brightest color in the palette, so it stands out. You can use the plt.axvline() function to draw a vertical line at the current year:
main.py
current_year = 2022  # Set the current year here
current_color = sns.light_palette("blue", n_colors=1)[-1]

plt.axvline(x=current_year, color=current_color, linestyle="--")
173 chars
5 lines
  1. Show the plot:
main.py
plt.show()
11 chars
2 lines

Here's the complete code:

main.py
import seaborn as sns
import matplotlib.pyplot as plt

# Step 2: Prepare your data
# Assuming you have a DataFrame named `df` with columns 'year' and 'value'

# Step 3: Define custom color palette
palette = sns.light_palette("blue", n_colors=len(df["year"].unique()), reverse=True)

# Step 4: Plot the line plot
sns.lineplot(data=df, x="year", y="value", hue="year", palette=palette)

# Step 5: Highlight the current year
current_year = 2022  # Set the current year here
current_color = sns.light_palette("blue", n_colors=1)[-1]

plt.axvline(x=current_year, color=current_color, linestyle="--")

# Step 6: Show the plot
plt.show()
631 chars
21 lines

This code will generate a line plot with a custom color palette where certain years appear lighter and the current year is highlighted.

gistlibby LogSnag