如何基于CSV数据制作与参考图一致的年度柱状图?
解决方案:调整Seaborn+Matplotlib代码匹配参考风格
参考图的核心特征包括:深色背景、渐变色彩柱体、柱子顶部数值标注、简化坐标轴样式。以下是修改后的代码:
import pandas as pd import seaborn as sns import matplotlib.pyplot as plt # 数据读取与预处理 box = pd.read_csv("box_office_18_23.csv") box["overall_gross"] = box["overall_gross"].str.replace("$", "").str.replace(",", "").astype(int) # 转换为百万美元单位,优化显示 box["gross_millions"] = box["overall_gross"] / 1_000_000 # 设置深色主题 sns.set_style("darkgrid", {"axes.facecolor": "#121212", "grid.color": "#333333"}) plt.figure(figsize=(10, 6), facecolor="#121212") # 绘制带渐变色彩的柱状图 bar_plot = sns.barplot( x="year", y="gross_millions", data=box, palette=["#ff416c", "#ff4b2b", "#ff8c00", "#ffd700", "#32cd32", "#1e90ff"] ) # 添加柱子顶部的数值标注 for p in bar_plot.patches: height = p.get_height() bar_plot.text( p.get_x() + p.get_width() / 2., height + 5, f"{height:.1f}M", ha="center", va="bottom", color="white", fontweight="bold" ) # 自定义坐标轴与标题样式 plt.xlabel("年份", color="white", fontsize=12) plt.ylabel("票房(百万美元)", color="white", fontsize=12) plt.title("年度票房总览", color="white", fontsize=16, pad=20) # 调整刻度与边框样式 bar_plot.tick_params(axis="x", colors="white") bar_plot.tick_params(axis="y", colors="white") bar_plot.spines[["right", "top"]].set_visible(False) bar_plot.spines[["left", "bottom"]].set_color("#555555") plt.tight_layout() plt.show()
其他可选工具
1. Plotly(交互式可视化)
Plotly可以快速实现参考图风格,还支持交互悬停效果:
import plotly.express as px fig = px.bar( box, x="year", y="gross_millions", color="year", color_discrete_sequence=["#ff416c", "#ff4b2b", "#ff8c00", "#ffd700", "#32cd32", "#1e90ff"], title="年度票房总览" ) fig.update_layout( plot_bgcolor="#121212", paper_bgcolor="#121212", font_color="white", xaxis_title="年份", yaxis_title="票房(百万美元)" ) fig.update_traces(texttemplate="%{y:.1f}M", textposition="outside") fig.show()
2. Altair(声明式可视化)
基于Vega-Lite,适合高度定制化的可视化需求,语法简洁易读,通过声明式语法即可实现复杂样式。
内容的提问来源于stack exchange,提问作者Mubashir Ahmed Siddiqui
相关产品推荐
相关产品推荐

