第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Seaborn catplot(kind='count') 條形圖轉餅圖

Seaborn catplot(kind='count') 條形圖轉餅圖

瀟瀟雨雨 2022-12-20 16:36:59
我有以下關于 corona-tracking-apps 的論文的 df(上面使用了 pd.melt):    CTQ-tool    opinion0   Information and awareness purposes  unacceptable1   Information and awareness purposes  unacceptable2   Information and awareness purposes  acceptable3   Information and awareness purposes  acceptable4   Information and awareness purposes  unacceptable... ... ...2827    Central/Local data storage  NaN2828    Central/Local data storage  NaN2829    Central/Local data storage  NaN2830    Central/Local data storage  NaN2831    Central/Local data storage  NaN2832 rows × 2 columns我正在使用 Seaborn 庫制作以下 catplot:代碼:g = sns.catplot("opinion", col="CTQ-tool", col_wrap=4, data=df_original_small, kind="count", height=6.5, aspect=.8)但是,我不想將它們顯示在條形圖中,而是將它們顯示為餅圖。Seaborn.catplot 不允許使用 kind='count-pie'。有誰知道解決方法?在 TiTo 問題后編輯:這基本上是我希望看到的所有 8 個條形圖發(fā)生的情況:
查看完整描述

3 回答

?
慕森卡

TA貢獻1806條經驗 獲得超8個贊

我最終使用 matplotlib 庫從底層構建它:


plt.style.use('seaborn')


IAP = df_original_small['Information and awareness purposes'].value_counts().to_frame().T

QE = df_original_small['Quarantine Enforcement'].value_counts().to_frame().T

CTCR = df_original_small['Contact Tracing and Cross-Referencing'].value_counts().to_frame().T

VPID = df_original_small['Voluntary provision of infection data'].value_counts().to_frame().T

QMA = df_original_small['Quarantine Monitoring App'].value_counts().to_frame().T

QRCode = df_original_small['QR code provided registration tracking'].value_counts().to_frame().T


total = pd.concat([IAP, QE, CTCR, VPID, QMA, QRCode])


fig, ax = plt.subplots(nrows=3, ncols=2)


labels = 'acceptable', 'unacceptable'

colors = ['#008fd5', '#fc4f30']

explode = (0, 0.1)

explode2 = (0.2, 0)


plt.title('Pie chart per CTQ-tool')

plt.tight_layout()


ax[0,0].pie(total.iloc[[0]], startangle=90, colors=colors, wedgeprops={'edgecolor': 'black'}, autopct='%1.f%%', explode=explode, shadow=True)

ax[0,0].set_title('Information and awareness purposes', fontweight='bold')

ax[0,1].pie(total.iloc[[1]],  startangle=90, colors=colors, wedgeprops={'edgecolor': 'black'}, autopct='%1.f%%', explode=explode, shadow=True)

ax[0,1].set_title('Quarantine Enforcement', fontweight='bold')

ax[1,0].pie(total.iloc[[2]],  startangle=90, colors=colors, wedgeprops={'edgecolor': 'black'}, autopct='%1.f%%', explode=explode2, shadow=True)

ax[1,0].set_title('Contact Tracing and Cross-Referencing', fontweight='bold')

ax[1,1].pie(total.iloc[[3]], startangle=90, colors=colors, wedgeprops={'edgecolor': 'black'}, autopct='%1.f%%', explode=explode, shadow=True)

ax[1,1].set_title('Voluntary provision of infection data', fontweight='bold')

ax[2,0].pie(total.iloc[[4]], startangle=90, colors=colors, wedgeprops={'edgecolor': 'black'}, autopct='%1.f%%', explode=explode2, shadow=True)

ax[2,0].set_title('Quarantine Monitoring App', fontweight='bold')

ax[2,1].pie(total.iloc[[5]], startangle=90, colors=colors, wedgeprops={'edgecolor': 'black'}, autopct='%1.f%%', explode=explode, shadow=True)

ax[2,1].set_title('QR code provided registration tracking', fontweight='bold')



fig.suptitle('Public Opinion on CTQ-measures', fontsize=20, y=1.07, fontweight='bold', x=0.37)

fig.set_figheight(10)

fig.set_figwidth(7)

fig.legend(loc='best', labels=labels, fontsize='medium')

fig.tight_layout()


fig.savefig('Opinions_ctq')


plt.show()

http://img1.sycdn.imooc.com//63a174750001dff604890761.jpg

查看完整回答
反對 回復 2022-12-20
?
慕婉清6462132

TA貢獻1804條經驗 獲得超2個贊

如果你想要快速的東西,你也可以試試這個:


import numpy as np

import pandas as pd

import matplotlib.pyplot as plt

import seaborn as sns


df = pd.DataFrame({'CTQ-tool':np.random.choice(['a','b','c','d'],50),

                  'opinion':np.random.choice(['acceptable','unacceptable'],50)})


fig, ax = plt.subplots(2,2)

ax = ax.flatten()

tab = pd.crosstab(df['CTQ-tool'],df['opinion'])

for i,cat in enumerate(tab.index):

    tab.loc[cat].plot.pie(ax=ax[i],startangle=90)

    ax[i].set_ylabel('')

    ax[i].set_title(cat, fontweight='bold')

http://img1.sycdn.imooc.com//63a174860001bc0903950246.jpg

查看完整回答
反對 回復 2022-12-20
?
慕標5832272

TA貢獻1966條經驗 獲得超4個贊

問題是關于創(chuàng)建餅圖,python所以我認為你可以使用另一個可視化庫,比如Plotly,除了作為一個可視化庫之外,Plotly它還是一個交互式可視化庫,所以你所有的圖表都是交互式的!


快速瀏覽一下餅圖文檔。


現在,對于你的問題,我創(chuàng)建了一個小數據集并創(chuàng)建了兩個餅圖來說明代碼的樣子。


首先,導入所需的庫:

import pandas as pd

import plotly.graph_objects as go

from plotly.subplots import make_subplots

from kaleido.scopes.plotly import PlotlyScope # this will be used to export the chart as static image

玩具數據集:

df = pd.DataFrame(

    {

        "CTQ-tool": [

            "Information and awareness purposes",

            "Information and awareness purposes",

            "Information and awareness purposes",

            "Information and awareness purposes",

            "Information and awareness purposes",

            "Information and awareness purposes",

            "Quarantine Enforcement",

            "Quarantine Enforcement",

            "Quarantine Enforcement",

            "Quarantine Enforcement",

            "Quarantine Enforcement",

            "Quarantine Enforcement",

        ],

        "opinion": [

            "unacceptable",

            "unacceptable",

            "unacceptable",

            "unacceptable",

            "acceptable",

            "unacceptable",

            "acceptable",

            "unacceptable",

            "acceptable",

            "unacceptable",

            "unacceptable",

            "unacceptable",

        ],

    }

)

保存獨特的不同工具:

tools = df["CTQ-tool"].unique()

創(chuàng)建聚合數據:

以下代碼將按工具類型和意見類型分組,然后counts為每個工具創(chuàng)建一個新列,用于存儲每種意見類型的計數。


df_agg = df.groupby(by=["CTQ-tool", "opinion"]).size().reset_index(name="counts")

新的數據框df_agg將是:


|      | CTQ-tool                           | opinion      | counts |

| ---: | :--------------------------------- | :----------- | -----: |

|    0 | Information and awareness purposes | acceptable   |      1 |

|    1 | Information and awareness purposes | unacceptable |      5 |

|    2 | Quarantine Enforcement             | acceptable   |      2 |

|    3 | Quarantine Enforcement             | unacceptable |      4 |

可視化數據(有趣的部分):由于這個玩具數據只有兩個不同的工具,我創(chuàng)建了一個sub-plot只有一行和兩列的工具,但您可以將其擴展為任意多的行/列。

fig = make_subplots(rows=1, cols=2, specs=[[{"type": "domain"}, {"type": "domain"}]])

然后分別添加每個圖表(您可以使用 for 循環(huán)來完成):


fig = make_subplots(rows=1, cols=2, specs=[[{"type": "domain"}, {"type": "domain"}]])


# Information and awareness purposes tool

fig.add_trace(

    go.Pie(

        values=df_agg[df_agg["CTQ-tool"] == tools[0]]["counts"],

        labels=df_agg[df_agg["CTQ-tool"] == tools[0]]["opinion"],

        pull=[0.2, 0.0],

        title=tools[0],

    ),

    1,

    1,

)


# Quarantine Enforcement tool

fig.add_trace(

    go.Pie(

        values=df_agg[df_agg["CTQ-tool"] == tools[1]]["counts"],

        labels=df_agg[df_agg["CTQ-tool"] == tools[1]]["opinion"],

        pull=[0.2, 0.0],

        title=tools[1],

    ),

    1,

    2,

)

更新圖表布局:

fig.update_layout(title_text="Public Opinion on CTQ-measures")


fig.show()

最后,導出為靜態(tài)圖像:

現在您已經準備好數據并對其進行可視化,是時候將其保存為圖像了。Plotly 的創(chuàng)作者為此構建了一個工具:Kaleido。


您可以簡單地使用它如下:


scope = PlotlyScope()

fig_name = "Public-Opinion-on-CTQ-measures"

with open(f"{fig_name}.png", "wb") as f:

    f.write(scope.transform(fig, "png"))

這個數字是:

http://img1.sycdn.imooc.com//63a174940001657606540409.jpg

查看完整回答
反對 回復 2022-12-20
  • 3 回答
  • 0 關注
  • 144 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號