使用 matplotlib 将 Pandas DataFrames 绘制成饼图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21090316/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 00:12:28  来源:igfitidea点击:

Plotting Pandas DataFrames in to Pie Charts using matplotlib

matplotlibpandaspie-chartdataframe

提问by Nilani Algiriyage

Is it possible to print a DataFrameas a pie chart using matplotlib? Thishas instructions for plotting lot of chart types including bar, histogram, scatter plot etc. But pie chart is missing?

是否可以DataFrame使用 matplotlib 将 a打印为饼图?有绘制许多图表类型的说明,包括条形图、直方图、散点图等。但是缺少饼图?

采纳答案by Dan Allan

import matplotlib.pyplot as plt
plt.pie(DataFrame([1,2,3]))

seems to work as expected. If the DataFrame has more than one column, it will raise.

似乎按预期工作。如果 DataFrame 有不止一列,它将引发。

回答by cmgerber

Pandas has this built in to the pd.DataFrame.plot(). All you have to do is use kind='pie'flag and tell it which column you want (or use subplots=Trueto get all columns). This will automatically add the labels for you and even do the percentage labels as well.

Pandas 已将其内置到pd.DataFrame.plot(). 您所要做的就是使用kind='pie'标志并告诉它您想要哪个列(或用于subplots=True获取所有列)。这将自动为您添加标签,甚至还会添加百分比标签。

import matplotlib.pyplot as plt

df.Data.plot(kind='pie')

To make it a little more customization you can do this:

要使其更具自定义性,您可以执行以下操作:

fig = plt.figure(figsize=(6,6), dpi=200)
ax = plt.subplot(111)

df.Data.plot(kind='pie', ax=ax, autopct='%1.1f%%', startangle=270, fontsize=17)

Where you tell the DataFramethat ax=ax. You can also use all the normal matplotlib plt.pie()flags as shown above.

你在哪里告诉DataFrame那个ax=ax。您还可以使用matplotlib plt.pie()如上所示的所有普通标志。

回答by user2314737

To plot a pie chart from a dataframe dfyou can use Panda's plot.pie:

要从数据框中绘制饼图,df您可以使用 Panda 的plot.pie

df.plot.pie(y='column_name')

Example:

例子:

import pandas as pd

df = pd.DataFrame({'activity': ['Work', 'Sleep', 'Play'],
                   'hours': [8, 10, 6]})
df.set_index('activity', inplace=True)
print(df)
#               hours
# activity       
# Work          8
# Sleep        10
# Play          6
plot = df.plot.pie(y='hours', figsize=(7, 7))

Note that the labels of the pie chart are the index entries, this is the reason for using set_indexto set the index to activity.

请注意,饼图的标签是索引条目,这就是使用set_index将索引设置为 的原因activity

To style the plot, you can use all those arguments that can be passed to DataFrame.plot(), here an example showing percentages:

要设置绘图样式,您可以使用所有可以传递给DataFrame.plot() 的参数,这里是一个显示百分比的示例:

plot = df.plot.pie(y='hours', title="Title", legend=False, \
                   autopct='%1.1f%%', explode=(0, 0, 0.1), \
                   shadow=True, startangle=0)

Pie chart from Pandas dataframe

来自 Pandas 数据框的饼图