Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从dataframe列生成多个图形_Python_Pandas_Matplotlib_Seaborn - Fatal编程技术网

Python 从dataframe列生成多个图形

Python 从dataframe列生成多个图形,python,pandas,matplotlib,seaborn,Python,Pandas,Matplotlib,Seaborn,我从一些数据中创建了一个dataframe,如下所示 df = pd.Dataframe({'Keys': ['key1','key2','key3'] 'Percentage':[63,37,89]} 我想创建3个图表,显示每个键的百分比。我以为这会很容易,但我能找到的只是如何创建一个包含所有3个键的图表 解决这个问题的快速方法是为每个关键点创建一些列表,并以此为基础制作图表,但有没有更有效的方法 编辑: 我想为每个关键点创建类似的内容 import m

我从一些数据中创建了一个dataframe,如下所示

df = pd.Dataframe({'Keys': ['key1','key2','key3']
                   'Percentage':[63,37,89]}
我想创建3个图表,显示每个键的百分比。我以为这会很容易,但我能找到的只是如何创建一个包含所有3个键的图表

解决这个问题的快速方法是为每个关键点创建一些列表,并以此为基础制作图表,但有没有更有效的方法

编辑:

我想为每个关键点创建类似的内容

import matplotlib.pyplot as plt

fig1, ax1 = plt.subplots()
labels = ['key1_yes','key1_no']
sizes = [63,37]

ax1.set_title('key1')

ax1.pie(sizes, labels=labels, autopct='%1.1f%%',
        shadow=True, startangle=90)

最后做了这样的事

import matplotlib.pyplot as plt

for index, row in new_data_df.iterrows():

    fig1, ax1 = plt.subplots(figsize=(5,5))
    labels = ['Yes','No']
    sizes = [row['Percentage'],row['1-Percentage']]

    ax1.set_title(row['Key'])

    ax1.pie(sizes, labels=labels, autopct='%1.2f%%', startangle=90, colors = ['gainsboro','dimgrey'])

如果您按照以下方式定义df:

import pandas as pd

df = pd.DataFrame({'key': ['key1', 'key1', 'key2', 'key2', 'key3', 'key3'],
                   'kind': ['yes', 'no', 'yes', 'no', 'yes', 'no'],
                   'n': [63, 37, 89, 11, 37, 63]})
df
    key kind   n
0  key1  yes  63
1  key1   no  37
2  key2  yes  89
3  key2   no  11
4  key3  yes  37
5  key3   no  63
然后你可以这样画:

import matplotlib.pyplot as plt
import seaborn as sns

def my_pie(n, kind, **kwargs):
    plt.pie(x = n, labels = kind)

g = sns.FacetGrid(df, col = 'key')
g.map(my_pie, 'n', 'kind')
产生