华域联盟 Python 使用Python实现绘制发散条形图

使用Python实现绘制发散条形图

目录

发散条形图用于简化多个组的比较。它的设计允许我们比较各组中的数值。它还帮助我们快速地想象出有利的和不利的或积极的和消极的反应。条形图由从中间开始的两个水平条的组合组成-一个条从右向左延伸,另一个从左向右延伸。条形的长度与它所代表的数值相对应。

通常,两个分叉的条形用不同的颜色表示。左边的值通常但不一定是负面或不满意的反应。

Python没有特定的函数来绘制发散条形图。另一种方法是使用hlines函数绘制具有一定线宽值的水平线,将其表示为水平条。

数据集

Mercedes Benz Car Sales Data

地址:

https://www.kaggle.com/datasets/luigimersico/mercedes-benz-car-sales-data

实现步骤

导入模块

导入或创建数据

预处理数据集并清除不必要的噪声

指定表示水平条的颜色

按升序对值进行排序

设置x轴和y轴的标签以及图表的标题

显示发散条形图

实现代码

import pandas as pd 
import matplotlib.pyplot as plt 
import string as str


# Creating a DataFrame from the CSV Dataset 
df = pd.read_csv("car_sales.csv", sep=';') 

# Separating the Date and Mercedes-Benz Cars unit sales (USA) 
df['car_sales_z'] = df.loc[:, ['Mercedes-Benz Cars unit sales (USA)']] 
df['car_sales_z'] = df['car_sales_z'] .str.replace( 
	',', '').astype(float) 

# Removing null value 
df.drop(df.tail(1).index, inplace=True) 

for i in range(35): 
	# Colour of bar chart is set to red if the sales 
	# is < 60000 and green otherwise 
	df['colors'] = ['red' if float( 
		x) < 60000 else 'green' for x in df['car_sales_z']] 

# Sort values from lowest to highest 
df.sort_values('car_sales_z', inplace=True) 

# Resets initial index in Dataframe to None 
df.reset_index(inplace=True) 

# Draw plot 
plt.figure(figsize=(14, 10), dpi=80) 

# Plotting the horizontal lines 
plt.hlines(y=df.index, xmin=60000, xmax=df.car_sales_z, 
		color=df.colors, alpha=0.4, linewidth=5) 

# Decorations 
# Setting the labels of x-axis and y-axis 
plt.gca().set(ylabel='Quarter', xlabel='Sales') 

# Setting Date to y-axis 
plt.yticks(df.index, df.Date, fontsize=12) 

# Title of Bar Chart 
plt.title('Diverging Bars Chart Example', fontdict={ 
		'size': 20}) 

# Optional grid layout 
plt.grid(linestyle='--', alpha=0.5) 

# Displaying the Diverging Bar Chart 
plt.show() 

效果图

到此这篇关于使用Python实现绘制发散条形图的文章就介绍到这了,更多相关Python发散条形图内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

本文由 华域联盟 原创撰写:华域联盟 » 使用Python实现绘制发散条形图

转载请保留出处和原文链接:https://www.cnhackhy.com/160428.htm

本文来自网络,不代表华域联盟立场,转载请注明出处。

作者: sterben

发表回复

联系我们

联系我们

2551209778

在线咨询: QQ交谈

邮箱: [email protected]

工作时间:周一至周五,9:00-17:30,节假日休息

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

关注微博
返回顶部