Pandas数据帧的堆积条形图

2024-10-02 14:19:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧'dft',其中有两列'Month'(可以是一月到十二月)和'expensation'(该月的数据)。在

我正试图为这些数据创建一个堆叠的条形图,堆栈表示0-100;100-500和500+之间的支出

为了对这些值的数据帧进行排序,我编写了以下代码。在

small = dft[(dft['Expenditure'] < 100) & (dft['Expenditure'] > 0)]
medium = dft[(dft['Expenditure'] <= 500) & (dft['Expenditure'] >= 100)]
large = dft[(dft['Expenditure'] > 500)] 

有没有一种方法可以直接从Pandas直接将这些数据帧绘制成一个堆积条形图?图表将有一个月的x轴和y轴的支出。在


Tags: 数据方法代码pandas排序堆栈smallmedium
2条回答

把我的评论变成一个答案:不是拆分数据帧,而是添加一个新的列和限定符来堆栈(small,medium,large)。然后按新列旋转框架并使用stacked=True选项打印。在

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# some data
dft = pd.DataFrame({"month" : ['January', 'October', 'November', 'December', 'January',
                               'June', 'July', 'August', 'September', 'October',
                               'November', 'December', 'January', 'November', 'December'],
                    "expediture" : [2.0, 91.53, 16.7, 50.4, 1240.3, 216.17, 310.77, 422.12,
                                    513.53, 113.53, 377.249, 1179.41, 156, 2354.33, 157.45]})

# possible labels / months
labels = ['small', 'medium', 'large']
months = pd.date_range('2014-01','2014-12', freq='MS').strftime("%B").tolist()
full = pd.DataFrame(columns=labels, index=months)

#quantize data
dft["quant"] = pd.cut(dft["expediture"], bins = [0,100,500,np.inf], labels=labels)
# pivot data
piv = dft.pivot(values='expediture',  columns="quant",  index = "month")
# update full with data to have all months/labels available, even if not
# present in original dataframe
full.update(piv)

full.plot.bar(stacked=True)

plt.show()

enter image description here

欢迎来到StackOverflow!在

我试图创建一个简单的示例(使用原始给定数据)来解决您的案例。您还应该查看文档中的stacked_bar_chart。要转换月份并“填充”数据,可以使用以下方法:

stacked bar chart

import numpy as np
import matplotlib.pyplot as plt

# given x data
x1 = ['January', 'October', 'November', 'December']
x2 = ['January', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
x3 = ['January', 'November', 'December']

# given y data
y1 = [2.0, 91.53, 16.7, 50.4]
y2 = [1240.3, 216.17, 310.77, 422.12, 513.53, 113.53, 377.249, 1179.41]
y3 = [15.6, 235.433, 574.45]

# save all months in a list
months = ['January',
          'February',
          'March',
          'April',
          'May',
          'June',
          'July',
          'August',
          'September',
          'October',
          'November',
          'December']

monthsDict = {}

# assign in a dictionary a number for each month
# 'January' : 0, 'February' : 1
for i, val in enumerate(months):
    monthsDict[val] = i


# this function converts the given datasets by you into full 12 months list
def to_full_list(x, y):

    # initialize a list of floats with a length of 12
    result = [0.0] * 12

    # assign for each months in the list the value to the corresponding index in result
    # x[0] = January, y[0] = 2.0 would be result[0] = 12.0
    for i, val in enumerate(x):
        result[monthsDict[val]] = y[i]

    return result


# convert the given data into the right format
r1 = np.array(to_full_list(x1, y1))
r2 = np.array(to_full_list(x2, y2))
r3 = np.array(to_full_list(x3, y3))

# increase the width of the output to match the long month strings
plt.figure(figsize=(11, 6))

# plot each of the created datasets
# x axis: months; y axis: values
p3 = plt.bar(months, r3 + r2 + r1)
p2 = plt.bar(months, r2 + r1)
p1 = plt.bar(months, r1)

# display the plot
plt.show()

相关问题 更多 >