考慮下表:
| 國家 | 積分 | 價格 |
|---|---|---|
| 英國 | 91.550725 | 51.681159 |
| 印度 | 90.222222 | 13.333333 |
| 奧地利 | 90.190782 | 30.762772 |
| 德國 | 89.836321 | 42.257547 |
| 加拿大 | 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)

我的問題:如何將右側的 Y 軸刻度引數修改為價格(紅色),以便它代表價格列的編號以及標題。
- 熊貓:1.2.4
- Seaborn:0.11.1
- Matplotlib:3.3.4
uj5u.com熱心網友回復:
我認為這接近你想要的:
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()
示例輸出:

但是,我希望您考慮到特倫頓在評論(現已洗掉)中提到的這一點。這張圖確實比較難讀。左邊的值在右邊有標簽,反之亦然。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/394390.html
標籤:Python matplotlib
上一篇:PyQt5和matplotlib,圖形僅在螢屏最大化或最小化時更新
下一篇:將共享軸標簽放在上圖
