首页 > 解决方案 > 带有2个变量python的条形图

问题描述

我有以下来自 excel 文件的数据框:

df = pd.read_excel('base.xlsx')

我的 excel 文件包含以下列:

我需要绘制一个条形图,其中 x 轴是日期,条形图是库存和需求。蓝色是需求,橙色是库存:

蓝色是需求,橙色是库存

标签: pythonpandasmatplotlibseaborn

解决方案


这可以通过 pandas 条形图功能来完成。请注意,如果您的数据集中没有记录日期(例如周末或国定假日),它们将不会自动显示在条形图中并带有间隙。这是因为 pandas(和其他包)中的条形图主要是为分类数据制作的,如此此处所述。

import numpy as np                 # v 1.19.2
import pandas as pd                # v 1.1.3
import matplotlib.pyplot as plt    # v 3.3.2

# Create a random time series with the date as index
# In your case where you are importing your dataset from excel you
# would assign your date column to the df index like this:
rng = np.random.default_rng(123)
days = 7
df = pd.DataFrame(dict(demand = rng.uniform(100, size=days),
                       stock = rng.uniform(100, size=days),
                       origin = np.random.choice(list('ABCD'), days)),
                  index = pd.date_range(start='2020-12-14', freq='D', periods=days))

# Create pandas bar plot
fig, ax = plt.subplots(figsize=(10,5))
df.plot.bar(ax=ax, color=['tab:blue', 'tab:orange'])

# Assign ticks with custom tick labels
# Date format codes for xticklabels:
# https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
plt.xticks(ax.get_xticks(), [ts.strftime('%A') for ts in df.index], rotation=0)
plt.legend(frameon=False)
plt.show()

barplot_2vars


推荐阅读