-1

I am trying to add data labels to a line chart that is part of a dual axis chart using matplotlib / seaborn, but can't seem to find a solution to get the labels to show

# Pandas for managing datasets
import pandas as pd

# Matplotlib for additional customization
from matplotlib import pyplot as plt
%matplotlib inline

# Seaborn for plotting and styling
import seaborn as sns

# Sample data
data = {'Performance Score': ['PIP', 'To Improve', 'Meet', 'Exceed'],
        'Employees by performance score': [2, 17, 201, 30],
        'Average Satisfaction': [1.5, 3.6, 3.9, 4.1]}
df = pd.DataFrame(data)

# Set theme for Chart A
sns.set_theme(style='dark',rc={'axes.facecolor':'White', 'figure.facecolor':'White'})
fig, ax1 = plt.subplots(figsize=(12,6))

# Plot dataset A as dual-axis chart
# Plot line chart as left y axis
sns.lineplot(data = df, y='Average Satisfaction',x='Performance Score', marker='o', sort = False, ax=ax1, color='#97b0df',label='Average Satisfaction')
ax2 = ax1.twinx()


# Plot bar chart as right y axis
sns.barplot(data = df, x = 'Performance Score', y = 'Employees by performance score', alpha=0.8, ax=ax2, color='#2c5494', label='Employees by Performance Score')

# Show values on bar chart
for i in ax2.containers:
    ax2.bar_label(i,)

df

  Performance Score  Employees by performance score  Average Satisfaction
0               PIP                               2                   1.5
1        To Improve                              17                   3.6
2              Meet                             201                   3.9
3            Exceed                              30                   4.1

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
  • by labels are you looking for a legend for the chart? if so, try `ax2.legend()` – Jonathan Aug 05 '22 at 11:11
  • The following line of code from the duplicates will annotate the points on the line. `for x, y in zip(df['Performance Score'], df['Average Satisfaction']): ax1.annotate(y, xy=(x, y), textcoords='data')` & `ax2.legend(loc='upper right', bbox_to_anchor=(1, 0.9))`. See [code and plot](https://i.stack.imgur.com/RMD8b.png) – Trenton McKinney Aug 05 '22 at 17:19

1 Answers1

0
fig, ax = plt.subplots(2,figsize=(12,8), sharex=False)
l = sns.lineplot(x='Performance Score', 
         y='Average Satisfaction',
         data = df, 
         ax=ax[0], 
         color='#97b0df',
         marker='o',
         sort = False,)

b =sns.barplot(x='Performance Score',
        y='Employees by performace score', 
        data = df, 
        ax=ax[1],
        alpha=0.8,
        color='#2c5494')

# you can use the set_xlabel() and set_ylabel to set the x and y-axis label respectively.


l.set_xlabel('Average Satisfaction') 
b.set_xlabel('Employees by Performance Score')