python - 带有2个变量python的条形图
问题描述
我有以下来自 excel 文件的数据框:
df = pd.read_excel('base.xlsx')
我的 excel 文件包含以下列:
- 数据 - datetime64[ns]
- 股票-float64
- 需求 - float64
- origem - 对象
我需要绘制一个条形图,其中 x 轴是日期,条形图是库存和需求。蓝色是需求,橙色是库存:
解决方案
这可以通过 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()
推荐阅读
- python - Gensim word2vec 模型是否与 Mikolov 的标准模型相同?
- python - python程序说2个数字相同时是不同的
- flutter - List.Builder 在 Flutter 中给出范围错误
- python - 从 django 查询集中获取日期值
- laravel - Laravel 搜索功能
- html - 角度材料输入并在单行的一个表单字段内选择
- sql - Exasol 中两个日期之间的天数列表
- android-studio - 无法在 Android Studio 3.6.3 中添加资产文件夹
- ruby-on-rails - 如何从rails中的elasticsearch中检索所有记录
- javascript - 为什么我应该使用匿名函数将我的函数存储为变量