视频讲解:优化柱状图

你好,我是郭震

AI数据可视化 第三集:美化柱状图,完整视频如下所示:

美化后效果前后对比,前:

af6b89a31fd964ac7c73f1d3f4308c2b.png

后:f49a7d141a60a6a7a4accb5052bed542.png

附完整案例源码:

util.py文件

import platform

def get_os():
    os_name = platform.system()
    if os_name == 'Windows':
        return "Windows"
    elif os_name == 'Darwin':
        return "macOS"
    else:
        return "Unknown OS"

优化后的柱状图,完整源码:

import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties

# 根据操作系统设置字体
from util import get_os

system_type = get_os()
if system_type == 'Windows':
    font = FontProperties(fname="C:\\Windows\\Fonts\\msyh.ttc", size=14)  # 注意路径分隔符的转义
elif system_type == 'macOS':
    font = FontProperties(fname="/System/Library/Fonts/PingFang.ttc", size=14)

# 咖啡店及其销售额数据
coffee_shops = ['咖啡店A', '咖啡店B', '咖啡店C', '咖啡店D', '咖啡店E']
sales = [1200, 1500, 1800, 1600, 2000]

# 自定义颜色列表
colors = ['#307EC7', '#AA4643', '#89A54E', '#71588F', '#4198AF']

plt.figure(figsize=(10, 6))

# 设置图表背景为科技黑
plt.gca().set_facecolor('#2B2B2B')
plt.gcf().set_facecolor('#2B2B2B')

bars = plt.bar(coffee_shops, sales, color=colors, edgecolor='#EEEEEE')  # 设置柱子边框为亮色

# 在柱子顶部添加数据标签
for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x() + bar.get_width()/2, yval + 50, yval, ha='center', va='bottom', color='#FFFFFF', fontproperties=font)  # 数据标签颜色改为白色

# 设置网格线样式
plt.grid(color='#555555', linestyle='--', linewidth=0.5, axis='y', zorder=0, alpha=0.7)

# 设置标签和标题颜色为亮色
plt.xticks(ticks=range(len(coffee_shops)), labels=coffee_shops, fontproperties=font, color='#FFFFFF')
plt.xlabel('咖啡店', fontproperties=font, color='#FFFFFF')
plt.ylabel('销售额(美元)', fontproperties=font, color='#FFFFFF')
plt.title('某小镇咖啡店一周销售额对比', fontproperties=font, color='#FFFFFF')
plt.yticks(fontsize=14, color='#FFFFFF')

# 设置图例,调整图例的背景和文字颜色
legend = plt.legend(bars, coffee_shops, prop=font)
frame = legend.get_frame()
frame.set_color('#2B2B2B')  # 图例背景色
frame.set_edgecolor('#EEEEEE')  # 图例边框色
plt.setp(legend.get_texts(), color='#FFFFFF')  # 图例文字颜色

plt.tight_layout()
plt.show()

相关推荐

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-02-13 06:20:01       94 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-02-13 06:20:01       101 阅读
  3. 在Django里面运行非项目文件

    2024-02-13 06:20:01       82 阅读
  4. Python语言-面向对象

    2024-02-13 06:20:01       91 阅读

热门阅读

  1. 动态态势感知中的态、势、感、知变化规律

    2024-02-13 06:20:01       50 阅读
  2. 缓存预热!真香

    2024-02-13 06:20:01       56 阅读
  3. c#异步编程

    2024-02-13 06:20:01       46 阅读
  4. C#系列-C#EF框架实现雪花主键(20)

    2024-02-13 06:20:01       43 阅读
  5. arduino ide编写的esp32和st773580*160的一个接球小游戏

    2024-02-13 06:20:01       64 阅读
  6. 洛谷:P1331 海战

    2024-02-13 06:20:01       53 阅读
  7. LeetCode79. Word Search——回溯

    2024-02-13 06:20:01       47 阅读
  8. C++Web头文件: Hacker.h

    2024-02-13 06:20:01       51 阅读