使用Python實(shí)現(xiàn)繪制發(fā)散條形圖
發(fā)散條形圖用于簡化多個組的比較。它的設(shè)計(jì)允許我們比較各組中的數(shù)值。它還幫助我們快速地想象出有利的和不利的或積極的和消極的反應(yīng)。條形圖由從中間開始的兩個水平條的組合組成-一個條從右向左延伸,另一個從左向右延伸。條形的長度與它所代表的數(shù)值相對應(yīng)。
通常,兩個分叉的條形用不同的顏色表示。左邊的值通常但不一定是負(fù)面或不滿意的反應(yīng)。
Python沒有特定的函數(shù)來繪制發(fā)散條形圖。另一種方法是使用hlines函數(shù)繪制具有一定線寬值的水平線,將其表示為水平條。
數(shù)據(jù)集
Mercedes Benz Car Sales Data
地址:
https://www.kaggle.com/datasets/luigimersico/mercedes-benz-car-sales-data
實(shí)現(xiàn)步驟
導(dǎo)入模塊
導(dǎo)入或創(chuàng)建數(shù)據(jù)
預(yù)處理數(shù)據(jù)集并清除不必要的噪聲
指定表示水平條的顏色
按升序?qū)χ颠M(jìn)行排序
設(shè)置x軸和y軸的標(biāo)簽以及圖表的標(biāo)題
顯示發(fā)散條形圖
實(shí)現(xiàn)代碼
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() 效果圖

到此這篇關(guān)于使用Python實(shí)現(xiàn)繪制發(fā)散條形圖的文章就介紹到這了,更多相關(guān)Python發(fā)散條形圖內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python中從str中提取元素到list以及將list轉(zhuǎn)換為str的方法
今天小編就為大家分享一篇python中從str中提取元素到list以及將list轉(zhuǎn)換為str的方法,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-06-06
python list刪除元素時要注意的坑點(diǎn)分享
下面小編就為大家分享一篇python list刪除元素時要注意的坑點(diǎn)分享,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2018-04-04
Python實(shí)現(xiàn)的維尼吉亞密碼算法示例
這篇文章主要介紹了Python實(shí)現(xiàn)的維尼吉亞密碼算法,結(jié)合實(shí)例形式分析了基于Python實(shí)現(xiàn)維尼吉亞密碼算法的定義與使用相關(guān)操作技巧,需要的朋友可以參考下2018-04-04
Python實(shí)現(xiàn)代碼統(tǒng)計(jì)工具
這篇文章主要為大家詳細(xì)介紹了Python實(shí)現(xiàn)代碼統(tǒng)計(jì)工具,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2019-09-09

