matplotlib 如何使用条形图绘制辅助y轴?

mfuanj7w  于 2023-10-24  发布在  其他
关注(0)|答案(1)|浏览(127)

我正在尝试绘制数据(见下文)。x轴上有company_name,y轴上有status_mission_2_y,另一个y轴上有percentage。我试过使用twinx()函数,但我不能让它工作。

  1. def twinplot(data):
  2. x_ = data.columns[0]
  3. y_ = data.columns[1]
  4. y_2 = data.columns[2]
  5. data1 = data[[x_, y_]]
  6. data2 = data[[x_, y_2]]
  7. plt.figure(figsize=(15, 8))
  8. ax = sns.barplot(x=x_, y=y_, data=data1)
  9. ax2 = ax.twinx()
  10. g2 = sns.barplot(x=x_, y=y_2, data=data2, ax=ax2)
  11. plt.show()
  12. data = ten_company_missions_failed
  13. twinplot(data)

| 公司名称|百分比|status_mission_2_y|
| --|--|--|
| EER| 1 | 1 |
| 戈特| 1 | 1 |
| TRV| 1 | 1 |
| 桑迪亚| 1 | 1 |
| 测试| 1 | 1 |
| 美国海军|0.823529412| 17 |
| Zed| 0.8| 5 |
| Gov| 0.75| 4 |
| 骑士|0.66666667| 3 |
| 有|0.66666667| 3 |

7tofc5zh

7tofc5zh1#

Seaborn用相同的颜色和相同的x位置绘制两个条形图。
下面的示例代码调整了条形图的宽度,将ax的条形图向左移动。将ax2的条形图向右移动。为了区分右侧的条形图,使用了半透明(alpha=0.7)和阴影。

  1. import matplotlib.pyplot as plt
  2. from matplotlib.ticker import PercentFormatter
  3. import pandas as pd
  4. import seaborn as sns
  5. from io import StringIO
  6. data_str = '''company_name percentage status_mission_2_y
  7. EER 1 1
  8. Ghot 1 1
  9. Trv 1 1
  10. Sandia 1 1
  11. Test 1 1
  12. "US Navy" 0.823529412 17
  13. Zed 0.8 5
  14. Gov 0.75 4
  15. Knight 0.666666667 3
  16. Had 0.666666667 3'''
  17. data = pd.read_csv(StringIO(data_str), delim_whitespace=True)
  18. x_ = data.columns[0]
  19. y_ = data.columns[1]
  20. y_2 = data.columns[2]
  21. data1 = data[[x_, y_]]
  22. data2 = data[[x_, y_2]]
  23. plt.figure(figsize=(15, 8))
  24. ax = sns.barplot(x=x_, y=y_, data=data1)
  25. width_scale = 0.45
  26. for bar in ax.containers[0]:
  27. bar.set_width(bar.get_width() * width_scale)
  28. ax.yaxis.set_major_formatter(PercentFormatter(1))
  29. ax2 = ax.twinx()
  30. sns.barplot(x=x_, y=y_2, data=data2, alpha=0.7, hatch='xx', ax=ax2)
  31. for bar in ax2.containers[0]:
  32. x = bar.get_x()
  33. w = bar.get_width()
  34. bar.set_x(x + w * (1- width_scale))
  35. bar.set_width(w * width_scale)
  36. plt.show()

一个更简单的替代方案是将barplotax结合起来,将lineplotax2结合起来。

  1. plt.figure(figsize=(15, 8))
  2. ax = sns.barplot(x=x_, y=y_, data=data1)
  3. ax.yaxis.set_major_formatter(PercentFormatter(1))
  4. ax2 = ax.twinx()
  5. sns.lineplot(x=x_, y=y_2, data=data2, marker='o', color='crimson', lw=3, ax=ax2)
  6. plt.show()

展开查看全部

相关问题