簡體   English   中英

Plot 一棒 plot 使用 Seaborn

[英]Plot a bar plot by using Seaborn

我是數據可視化的新手。 我正在練習 Seaborn 並且我正在嘗試使用 dataframe 制作 plot 條形圖。 我希望圖表在每個符號上有 3 個柱,但是,output 每個符號只有 1 個柱。 我可以知道如何解決嗎?

DataFrame部分...

        returns_7d  returns_30d returns_ytd
symbol          
TDOC    -0.210839   -17.712095  -3.922423
EXAS    -4.649067   -6.439275   -1.415680
PACB    -2.953760   11.886232   37.815711
REGN    0.465364    5.803325    -0.629814
TWST    6.707956    3.619967    10.4043

像這樣的代碼:

import matplotlib.pyplot as plt
%matplotlib inline
import seaborn as sns

# Change the style of the figure to the "dark" theme
sns.set_style("darkgrid")

plt.figure(figsize=(12,6))
plt.title('YTD Returns')

sns.barplot(x=returns_all.index,y=returns_all['returns_7d'],color='b',edgecolor='w',label='returns_7d')
sns.barplot(x=returns_all.index,y=returns_all['returns_30d'],color='r',edgecolor='w',label='returns_30d')
sns.barplot(x=returns_all.index,y=returns_all['returns_ytd'],color='g',edgecolor='w',label='returns_ytd')


plt.xlabel('symbol', fontsize=11)
plt.ylabel('%', fontsize=11)
plt.xticks(rotation = 90)
plt.legend()
plt.show()

Output 像這樣:

在此處輸入圖像描述

我認為pandas.DataFrame.plot()就是你所需要的。

df.plot(kind='bar')

在此處輸入圖像描述

要使用 seaborn 創建這樣的 plot,請注意 seaborn 更喜歡“長格式”的數據。 reset_index將索引轉換為常規列,並將melt轉換為<variable, value>對。

import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from io import StringIO

data_str = '''   returns_7d  returns_30d returns_ytd  
TDOC    -0.210839   -17.712095  -3.922423
EXAS    -4.649067   -6.439275   -1.415680
PACB    -2.953760   11.886232   37.815711
REGN    0.465364    5.803325    -0.629814
TWST    6.707956    3.619967    10.4043'''
df = pd.read_csv(StringIO(data_str), delim_whitespace=True)
df.index.name = 'symbol'
df_long = df.reset_index().melt(id_vars='symbol')

sns.barplot(data=df_long, x='symbol', y='value', hue='variable', palette='rocket')
plt.show()

seaborn barplot 與長格式的列

長 dataframe 看起來像:

   symbol     variable      value
0    TDOC   returns_7d  -0.210839
1    EXAS   returns_7d  -4.649067
2    PACB   returns_7d  -2.953760
3    REGN   returns_7d   0.465364
4    TWST   returns_7d   6.707956
5    TDOC  returns_30d -17.712095
6    EXAS  returns_30d  -6.439275
7    PACB  returns_30d  11.886232
8    REGN  returns_30d   5.803325
9    TWST  returns_30d   3.619967
10   TDOC  returns_ytd  -3.922423
11   EXAS  returns_ytd  -1.415680
12   PACB  returns_ytd  37.815711
13   REGN  returns_ytd  -0.629814
14   TWST  returns_ytd  10.404300

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM