Python可视化 --柱形图

本文绘制以上6种类型的柱状图

1.matplotlib模块

   使用pyplot的bar()函数可以快速绘制柱形图或堆积图柱形图。八日()函数的语法格式如下:

bar(x,height,width=0.8,bottom=None,aqlign='center',
data=None,tick_label=None,xerr=None,yerr=None,
error_kw=None,**kwargs)

bar 函数是 Matplotlib 中用于绘制柱状图的函数,以下是参数的解释:

  • x: 一个数组,表示每个柱的 x 坐标。
  • height: 一个数组,表示每个柱的高度。
  • width: 可选参数,表示每个柱的宽度,默认为 0.8。
  • bottom: 可选参数,表示每个柱的底部位置,默认为 None,即从 0 开始。
  • align: 可选参数,表示柱的对齐方式,可选值为 'center'(默认)、'edge'。
  • data: 可选参数,是一个 DataFrame 或类似结构的数据,用于指定数据源。
  • tick_label: 可选参数,用于设置 x 轴刻度标签。
  • xerr: 可选参数,用于设置 x 方向的误差条(error bars)。
  • yerr: 可选参数,用于设置 y 方向的误差条(error bars)。
  • error_kw: 可选参数,用于设置误差条的样式。
  • **kwargs: 其他关键字参数,用于设置柱状图的样式属性,例如颜色、透明度等。

基础图

(1)

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(5)
y1 = np.array([10,8,7,11,13])
bar_width = 0.3
plt.bar(x,y1,tick_label=['a','b','c','d','e'],width=bar_width)
plt.show()

(2)

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

x = np.arange(5)
y1 = np.array([10, 8, 7, 11, 13])
bar_width = 0.3
plt.bar(x, y1, tick_label=['a', 'b', 'c', 'd', 'e'], width=bar_width)

# 使用 Seaborn 库中的 despine() 函数去除轴线
sns.despine()

plt.show()

(3)

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

x = np.arange(5)
y1 = np.array([10, 8, 7, 11, 13])
bar_width = 0.3
bars = plt.bar(x, y1, tick_label=['a', 'b', 'c', 'd', 'e'], width=bar_width)

sns.despine(left=True, bottom=True)  # 去除所有图脊
plt.yticks([])  # 不显示纵坐标

# 在每个柱形顶部显示数值
for bar in bars:
    yval = bar.get_height()
    plt.text(bar.get_x() + bar.get_width() / 2, yval, round(yval, 1), ha='center', va='bottom')

plt.show()

  1. import numpy as np: 导入 NumPy 库,用于处理数组等数值计算。

  2. import matplotlib.pyplot as plt: 导入 Matplotlib 的 pyplot 模块,用于绘制图形。

  3. import seaborn as sns: 导入 Seaborn 库,用于美化图形。

  4. x = np.arange(5): 创建一个包含 0 到 4 的数组作为 x 轴坐标。

  5. y1 = np.array([10, 8, 7, 11, 13]): 创建一个包含柱形高度数据的 NumPy 数组。

  6. bar_width = 0.3: 设置柱形的宽度为 0.3。

  7. bars = plt.bar(x, y1, tick_label=['a', 'b', 'c', 'd', 'e'], width=bar_width): 绘制柱状图,指定 x 轴、柱形高度数据、标签和宽度,并将返回的柱形对象存储在 bars 中。

  8. sns.despine(left=True, bottom=True): 使用 Seaborn 库中的 despine() 函数去除图形周围的轴线,通过设置 left=True, bottom=True 参数去除左侧和底部的轴线。

  9. plt.yticks([]): 不显示纵坐标刻度。

  10. 遍历每个柱形对象 bar,获取其高度并在顶部显示数值:

  • bar.get_x() + bar.get_width() / 2:计算文本标签的 x 坐标,使其居中于柱形。
  • bar.get_height():获取柱形的高度作为要显示的数值。
  • round(yval, 1):对数值进行四舍五入取一位小数。
  • plt.text(..., ha='center', va='bottom'):在指定位置添加文本标签,水平居中、垂直底部对齐,显示数值。
  1. plt.show(): 展示绘制的柱状图。

分组柱状图

(1)

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(5)
y1 = np.array([10,8,7,11,13])
y2 = np.array([9,6,5,10,12])
#柱形的宽度
bar_width = 0.3
#根据多组数据绘制柱形图
plt.bar(x,y1,tick_label=['a','b','c','d','e'],width=bar_width)
plt.bar(x+bar_width,y2,width=bar_width)
plt.show()

(2)

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(5)
y1 = np.array([10,8,7,11,13])
y2 = np.array([9,6,5,10,12])
#柱形的宽度
bar_width = 0.3
#根据多组数据绘制柱形图
plt.bar(x,y1,tick_label=['a','b','c','d','e'],color='dodgerblue',alpha=0.5,label='Male',width=bar_width)
plt.bar(x+bar_width,y2,color='tomato',alpha=0.5,label='Female',width=bar_width)
plt.legend() #显示图例
plt.show()

堆积柱状图

(1)

import numpy as np
import matplotlib.pyplot as plt
x = np.arange(5)
y1 = np.array([10,8,7,11,13])
y2 = np.array([9,6,5,10,12])
#柱形的宽度
bar_width = 0.3
#根据多组数据绘制柱形图
plt.bar(x,y1,tick_label=['a','b','c','d','e'],color='dodgerblue',alpha=0.5,label='Male',width=bar_width)
plt.bar(x,y2,bottom=y1,color='tomato',alpha=0.5,label='Female',width=bar_width)
plt.legend() #显示图例
plt.show()

百分比柱状图

import numpy as np
import matplotlib.pyplot as plt

x = np.arange(5)
y1 = np.array([10, 8, 7, 11, 13])
y2 = np.array([9, 6, 5, 10, 12])

# 计算百分比
total = y1 + y2
y1_percent = (y1 / total) * 100
y2_percent = (y2 / total) * 100

# 柱形的宽度
bar_width = 0.3

# 根据百分比数据绘制柱形图
plt.bar(x, y1_percent, tick_label=['a', 'b', 'c', 'd', 'e'], color='dodgerblue', alpha=0.5, label='Male', width=bar_width)
plt.bar(x, y2_percent, bottom=y1_percent, color='tomato', alpha=0.5, label='Female', width=bar_width)

plt.legend()  # 显示图例
plt.show()

  • 25
    点赞
  • 52
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要使用Python进行可视化柱形图,可以使用Matplotlib或Seaborn库。下面是使用这两个库的示例代码: 使用Matplotlib库: ```python import matplotlib.pyplot as plt import numpy as np # 准备数据 categories = ['A', 'B', 'C', 'D'] values = [10, 15, 8, 12] # 设置柱宽和位置 bar_width = 0.3 x = np.arange(len(categories)) # 绘制柱形图 plt.bar(x, values, width=bar_width) # 添加标签和图例 plt.xticks(x, categories) plt.xlabel('Categories') plt.ylabel('Values') plt.legend(['Bar']) # 显示图形 plt.show() ``` 使用Seaborn库: ```python import seaborn as sns # 准备数据 categories = ['A', 'B', 'C', 'D'] values = [10, 15, 8, 12] # 创建DataFrame df = pd.DataFrame({'Categories': categories, 'Values': values}) # 绘制柱形图 sns.barplot(x='Categories', y='Values', data=df) # 显示图形 plt.show() ``` 以上代码中,首先准备了要显示的数据,然后使用Matplotlib或Seaborn库的相关函数绘制柱形图。可以根据需要自定义图形的样式和布局。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [【python可视化-柱状图](https://blog.csdn.net/weixin_44411175/article/details/122753832)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值