【问题标题】:How to use fill_between() in python?如何在 python 中使用 fill_between()?
【发布时间】:2019-07-23 07:38:30
【问题描述】:

我有一个图表,想要填充图表与某个值相交的背景。 (在我的示例中为 0.75) 我使用以下代码:

fig, ax = plt.subplots()


df2 = pd.read_csv('kcfsinew2.csv')
x=df2['Date']
y=df2['KCFSI']
ax.plot(x, y , color='black')

theta = 0.75
ax.axhline(theta, color='grey', lw=2, alpha=0.5)
ax.fill_between(x , -1 , 6, where= y > theta ,facecolor='grey', alpha=0.5, transform=trans)

我得到的图像没有给我预期的输出,我不知道我的代码有什么问题。

【问题讨论】:

  • 您的代码中的 y 是什么?
  • 只需编辑我的帖子并添加 y。
  • 尝试用 theta 替换 2nd 和 3d 参数:ax.fill_between(x ,theta,where=y>theta,...
  • @Dennis 请将您的问题转换为minimal work example。对于您的特定代码,请将csv 文件替换为一些虚构数据,以便每个人都可以通过复制/粘贴来运行您的示例。
  • 除非您提供可运行的代码,否则读者很难在这里为您提供帮助。

标签: python pandas dataframe matplotlib


【解决方案1】:
  1. 使用fill_between方法填充行间
  2. 设置参数y2=0.75 以显示您希望图表底部的位置
  3. 设置您的参数where=df.y > 0.75,使其仅填充到 0.75 以上
  4. 设置参数interpolate=True,使其在每次线条交叉时填充

代码示例:

import pandas as pd # '0.23.4'
import numpy as np # '1.15.1'
import matplotlib # '2.2.3'
import matplotlib.pyplot as plt
import seaborn as sns; sns.set() # '0.9.0'

# set seed
np.random.seed(1)

# make df
df = pd.DataFrame(np.random.uniform(-1, 3, (30,)), index=pd.DatetimeIndex(start='20180101', periods=30, freq='3D'), columns=['y'])

# figure
fig, ax = plt.subplots()

# plot
df.plot(figsize=(16,8), ax=ax)

# draw line
ax.axhline(0.75, color='k')

# annotate
ax.text(0, 0.75, '0.75', transform=ax.get_yaxis_transform(), ha='right', )

# fill between y=0.75 and df.y
ax.fill_between(x=df.index, y1=df.y, y2=0.75, where=df.y > 0.75, interpolate=True)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多