python数据可视化代码_5 种使用 Python 代码轻松实现数据可视化的方法

柱状图

当你试图将类别很少(可能小于10)的分类数据可视化的时候,柱状图是最有效的。如果我们有太多的分类,那么这些柱状图就会非常杂乱,很难理解。柱状图对分类数据很好,因为你可以很容易地看到基于柱的类别之间的区别(比如大小);分类也很容易划分和用颜色进行编码。我们将会看到三种不同类型的柱状图:常规的,分组的,堆叠的。在我们进行的过程中,请查看图形下面的代码。

常规的柱状图如下面的图1。在 barplot() 函数中,xdata 表示 x 轴上的标记,ydata 表示 y 轴上的杆高度。误差条是一条以每条柱为中心的额外的线,可以画出标准偏差。

分组的柱状图让我们可以比较多个分类变量。看看下面的图2。我们比较的第一个变量是不同组的分数是如何变化的(组是G1,G2,……等等)。我们也在比较性别本身和颜色代码。看一下代码,y_data_list 变量实际上是一个 y 元素为列表的列表,其中每个子列表代表一个不同的组。然后我们对每个组进行循环,对于每一个组,我们在 x 轴上画出每一个标记;每个组都用彩色进行编码。

堆叠柱状图可以很好地观察不同变量的分类。在图3的堆叠柱状图中,我们比较了每天的服务器负载。通过颜色编码后的堆栈图,我们可以很容易地看到和理解哪些服务器每天工作最多,以及与其他服务器进行比较负载情况如何。此代码的代码与分组的条形图相同。我们循环遍历每一组,但这次我们把新柱放在旧柱上,而不是放在它们的旁边。

152056_qcRh_2896879.png

152106_K9eG_2896879.png

152114_U7g0_2896879.pngdef barplot(x_data, y_data, error_data, x_label="", y_label="", title=""):

_, ax = plt.subplots()

# Draw bars, position them in the center of the tick mark on the x-axis

ax.bar(x_data, y_data, color = '#539caf', align = 'center')

# Draw error bars to show standard deviation, set ls to 'none'

# to remove line between points

ax.errorbar(x_data, y_data, yerr = error_data, color = '#297083', ls = 'none', lw = 2, capthick = 2)

ax.set_ylabel(y_label)

ax.set_xlabel(x_label)

ax.set_title(title)

def stackedbarplot(x_data, y_data_list, colors, y_data_names="", x_label="", y_label="", title=""):

_, ax = plt.subplots()

# Draw bars, one category at a time

for i in range(0, len(y_data_list)):

if i == 0:

ax.bar(x_data, y_data_list[i], color = colors[i], align = 'center', label = y_data_names[i])

else:

# For each category after the first, the bottom of the

# bar will be the top of the last category

ax.bar(x_data, y_data_list[i], color = colors[i], bottom = y_data_list[i - 1], align = 'center', label = y_data_names[i])

ax.set_ylabel(y_label)

ax.set_xlabel(x_label)

ax.set_title(title)

ax.legend(loc = 'upper right')

def groupedbarplot(x_data, y_data_list, colors, y_data_names="", x_label="", y_label="", title=""):

_, ax = plt.subplots()

# Total width for all bars at one x location

total_width = 0.8

# Width of each individual bar

ind_width = total_width / len(y_data_list)

# This centers each cluster of bars about the x tick mark

alteration = np.arange(-(total_width/2), total_width/2, ind_width)

# Draw bars, one category at a time

for i in range(0, len(y_data_list)):

# Move the bar to the right on the x-axis so it doesn't

# overlap with previously drawn ones

ax.bar(x_data + alteration[i], y_data_list[i], color = colors[i], label = y_data_names[i], width = ind_width)

ax.set_ylabel(y_label)

ax.set_xlabel(x_label)

ax.set_title(title)

ax.legend(loc = 'upper right')

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值