Home > Back-end >  Two different graph ticks parameters on Y axes from one table
Two different graph ticks parameters on Y axes from one table

Time:12-26

Considering below table:

country points price
England 91.550725 51.681159
India 90.222222 13.333333
Austria 90.190782 30.762772
Germany 89.836321 42.257547
Canada 89.377953 35.712598
d = {'points': [91.5, 90.2, 90.1, 89.8, 89.3], 
'price': [51.6, 13.3,30.7, 42.2, 35.7]}
index=['England', 'India','Austria', 'Germany','Canada']
df = pd.DataFrame(index=index,data=d)

fig, ax1 = plt.subplots(figsize = (10,5))
color = 'tab:purple'
ax1.set_xlabel('Country', fontsize=12)
ax1.set_ylabel('Average Ratings', color=color, fontsize=12)
sns.barplot(x=df['points'],y=df.index, color=color)
ax1.tick_params(axis='y', labelcolor=color, labelsize = 12)

ax2 = ax1.twinx()  
plt.xlim(12, 92)

color = 'tab:red'
ax2.set_ylabel('Price', color=color, fontsize=12)  
sns.barplot(x=df['price'],y=df.index,color=color)
ax2.tick_params(axis='y', labelcolor=color, labelsize = 12) 

enter image description here

My question: How can I modify the right side Y axis ticks parameters to price (red), so that it represents the numbers of price column as well as the title.

  • Pandas: 1.2.4
  • Seaborn: 0.11.1
  • Matplotlib: 3.3.4

CodePudding user response:

I assume this comes close to what you want:

import pandas as pd
import seaborn as sns
from matplotlib import pyplot as plt

d = {'points': [91.5, 90.2, 90.1, 89.8, 89.3], 
'price': [51.6, 13.3,30.7, 42.2, 35.7]}
index=['England', 'India','Austria', 'Germany','Canada']
df = pd.DataFrame(index=index,data=d)

fig, ax1 = plt.subplots(figsize = (10,5))
color = 'tab:purple'
#ax1.set_xlabel('Country', fontsize=12) <-- not necessary for your output
ax1.set_ylabel('Average country rating (in points)', color=color, fontsize=12) #mention unit for rating
sns.barplot(x=df['points'],y=df.index, color=color)
ax1.tick_params(axis='y', labelcolor=color, labelsize = 12)

ax2 = ax1.twinx()
plt.xlim(12, 92)

color = 'tab:red'
ax2.set_ylabel('Price (in $)', color=color, fontsize=12)  #mention unit for price
sns.barplot(x=df['price'],y=df.index,color=color)
ax2.tick_params(axis='y', labelcolor=color, labelsize = 12) 
ax2.set_yticklabels(df['price']) #relabel right axis with price values
ax1.set_xlabel("") #remove x-label because this axis applies to both categories

plt.show()

Sample output: enter image description here

However, I hope you take the point into account that Trenton mentioned in a comment (now deleted). This graph is indeed rather difficult to read. The values on the left have their labels on the right, and vice versa.

  • Related