使用 matplotlib python 進行多軸 x

WBOY
發布: 2024-02-09 18:12:04
轉載
1130 人瀏覽過

使用 matplotlib python 进行多轴 x

問題內容

我的目標是得到如下圖的東西:

目前我嘗試像這樣建構它:

import matplotlib.pyplot as plt
import numpy as np 

X = ['Class 1','Class 2','Class 3','Class 4', 'Class 5', 'Class 6', 'Class 7'] 

sE = ['-9,51', '-13,5', '0,193', '9,564', '23,13', '-0,252', '-0,442']
s = ['19,605', '28,388', '1,762', '-4,264', '-24,716', '-26,956', '0,382']
eE = ['-5,364', '-7,954', '-3,756', '-0,184', '1,883', '41,876', '-0,012']


X_axis = np.arange(len(X)) 

# plt.bar(X_axis, sE, color='red',width = 0.25, edgecolor='black') 
# plt.bar(X_axis+0.25, s, color='cyan',width = 0.25, edgecolor='black') 
# plt.bar(X_axis+0.5, eE, color='green',width = 0.25, edgecolor='black') 

#plt.hist([sE, s, eE], color = ['red', 'cyan', 'green'], edgecolor = 'black', histtype = 'bar')

#plt.xticks(X_axis, X) 
plt.xlabel("Classes")  
plt.title("Geographical STP A") 
plt.show()
登入後複製

但我們距離達到預期結果還有很長的路要走。我真的不知道該怎麼做,你能幫我嗎?


正確答案


為了能夠繪圖,字串要轉換為數字。

使用基於 matplotlib 進行繪圖的 pandas(或 seaborn)庫,每個 x 值具有多個條形的繪圖要容易得多。您的數據沒有直方圖數據,您似乎想要一個長條圖。

這是一些程式碼。許多定制都是可能的。

import matplotlib.pyplot as plt
import pandas as pd

x = ['class 1', 'class 2', 'class 3', 'class 4', 'class 5', 'class 6', 'class 7']

se = ['-9,51', '-13,5', '0,193', '9,564', '23,13', '-0,252', '-0,442']
s = ['19,605', '28,388', '1,762', '-4,264', '-24,716', '-26,956', '0,382']
ee = ['-5,364', '-7,954', '-3,756', '-0,184', '1,883', '41,876', '-0,012']

# organize the data as a pandas dataframe
df = pd.dataframe({'class': x, 'se': se, 's': s, 'ee': ee})

# convert strings to numeric
df['se'] = df['se'].str.replace(',','.').astype(float)
df['s'] = df['s'].str.replace(',','.').astype(float)
df['ee'] = df['ee'].str.replace(',','.').astype(float)

ax = df.set_index('class').plot(kind='bar')

ax.set_title("geographical stp a")
ax.tick_params(axis='x', rotation=0)

plt.show()
登入後複製

可能的自訂可能包括:

ax = df.set_index('Class').plot(kind='bar', color=['crimson', 'limegreen', 'dodgerblue'])

ax.set_title("Geographical STP A")
ax.tick_params(axis='x', rotation=0, length=0)  # rotate tick labels horizontally, remove tick mark
ax.grid(True, axis='y')  # add a grid in the y direction
ax.set_xlabel('')  # remove superfluous x label
for dir in ['top', 'bottom', 'right']:
    ax.spines[dir].set_visible(False)  # remove the border around the plot
登入後複製

ps:資料框如下所示:

類別 se s ee 标题> 1 類別 -9.51 19.605 -5.364 2 類別 -13.5 28.388 -7.954 3 級 0.193 1.762 -3.756 4 類別 9.564 -4.264 -0.184 5 級 23.13 -24.716 1.883 6 級 -0.252 -26.956 41.876 7 類別 -0.442 0.382 -0.012 表>

以上是使用 matplotlib python 進行多軸 x的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!