You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Python在同一柱状图中绘制GDP与生物燃料产量双变量?

实现双变量同图柱状图的解决方案

我拥有一个名为“Merging2”的数据集,包含各国的GDP(rgdpe)和生物燃料产量(biofuel_production)数据。我想要绘制2019年GDP排名前五国家的柱状图,并在同一图表中展示这些国家的生物燃料产量柱状图。

我已编写绘制GDP柱状图的代码如下:

yr=Merging2.groupby(by='Years')
access1=yr.get_group(2019)
sorted=access1.sort_values(["rgdpe"], ascending=[False]) #进行排序
highest_gdp_2019=sorted.head(10) #取GDP排名靠前的10个数据(注:用户需求为前五)
fig, ax=plt.subplots()
plt.bar(highest_gdp_2019.Countries,highest_gdp_2019.rgdpe, color ='black',width = 0.8,alpha=0.8)
ax.set_xlabel("Countries")
ax.set_ylabel("Real GDP")
plt.xticks(rotation = 90)

请问能否在Python中实现上述双变量同图柱状图的绘制?

当然可以实现,针对你的需求,这里提供两种常见的可视化方案,适配不同的数据量级场景:

第一步:修正数据预处理逻辑

首先修正原代码中取Top10的错误,同时避免使用内置函数名作为变量名:

import matplotlib.pyplot as plt

# 筛选2019年数据并排序取GDP前五的国家
yr = Merging2.groupby(by='Years')
access1 = yr.get_group(2019)
# 用sorted_df替代sorted,避免覆盖Python内置函数
sorted_df = access1.sort_values(["rgdpe"], ascending=[False])
highest_gdp_2019 = sorted_df.head(5)

方式1:并排双柱状图(适合量级相近的变量)

通过调整柱子宽度和位置,让两类数据的柱子并排展示,便于横向对比:

fig, ax = plt.subplots(figsize=(8, 6))
bar_width = 0.35
x = range(len(highest_gdp_2019.Countries))

# 绘制GDP柱状图
ax.bar([i - bar_width/2 for i in x], highest_gdp_2019.rgdpe, 
       width=bar_width, color='black', alpha=0.8, label='Real GDP')
# 绘制生物燃料产量柱状图
ax.bar([i + bar_width/2 for i in x], highest_gdp_2019.biofuel_production, 
       width=bar_width, color='forestgreen', alpha=0.8, label='Biofuel Production')

# 配置图表属性
ax.set_xlabel("Countries")
ax.set_ylabel("Value")
ax.set_title("Top 5 Countries by GDP (2019) with Biofuel Production")
ax.set_xticks(x)
ax.set_xticklabels(highest_gdp_2019.Countries, rotation=90)
ax.legend()

plt.tight_layout()
plt.show()

方式2:双Y轴柱状图(适合量级差异大的场景)

由于GDP和生物燃料产量的数值量级通常差距极大,双Y轴能更清晰地展示两类数据的趋势:

fig, ax1 = plt.subplots(figsize=(8, 6))

# 左侧Y轴:GDP数据
color = 'black'
ax1.set_xlabel('Countries')
ax1.set_ylabel('Real GDP', color=color)
ax1.bar(highest_gdp_2019.Countries, highest_gdp_2019.rgdpe, 
        color=color, alpha=0.8, label='Real GDP')
ax1.tick_params(axis='y', labelcolor=color)
ax1.set_xticklabels(highest_gdp_2019.Countries, rotation=90)

# 右侧Y轴:生物燃料产量数据
ax2 = ax1.twinx()
color = 'forestgreen'
ax2.set_ylabel('Biofuel Production', color=color)
ax2.bar(highest_gdp_2019.Countries, highest_gdp_2019.biofuel_production, 
        color=color, alpha=0.6, label='Biofuel Production')
ax2.tick_params(axis='y', labelcolor=color)

# 配置标题和图例
fig.suptitle("Top 5 Countries by GDP (2019) with Biofuel Production")
# 合并两个轴的图例
lines1, labels1 = ax1.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax1.legend(lines1 + lines2, labels1 + labels2, loc='upper left')

plt.tight_layout()
plt.show()

额外提示

  • 如果biofuel_production字段存在缺失值,建议先执行highest_gdp_2019 = highest_gdp_2019.dropna(subset=['biofuel_production'])处理,避免绘图报错。
  • 可根据需求调整柱子颜色、宽度、图表尺寸等参数,优化可视化效果。

内容的提问来源于stack exchange,提问作者Aroune

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 15:55:26