python - PyPlot 中 x 轴和图形之间的颜色

标签 python matplotlib

我有一个使用日期时间对象绘制 x 轴的图表,我希望能够在图表本身(y 值)和 x 轴下方着色。我找到了这篇文章Matplotlib's fill_between doesnt work with plot_date, any alternatives?描述了类似的问题,但提出的解决方案对我根本没有帮助。

我的代码:

import matplotlib.patches as mpatches
import matplotlib.dates
import matplotlib.pyplot as plt
import numpy as np
import csv
from tkinter import *
from datetime import datetime
from tkinter import ttk

columns="YEAR,MONTH,DAY,HOUR,PREC,PET,Q,UZTWC,UZFWC,LZTWC,LZFPC,LZFSC,ADIMC,AET"
data_file="FFANA_000.csv"

UZTWC  = np.genfromtxt(data_file, 
                            delimiter=',', 
                            names=columns, 
                            skip_header=1, 
                            usecols=("UZTWC"))

list_of_datetimes = []
skipped_header = False;
with open(data_file, 'rt') as f:
    reader = csv.reader(f, delimiter=',', quoting=csv.QUOTE_NONE)
    for row in reader:
        if skipped_header:
            date_string = "%s/%s/%s %s" % (row[0].strip(), row[1].strip(), row[2].strip(), row[3].strip())
            dt = datetime.strptime(date_string, "%Y/%m/%d %H")
            list_of_datetimes.append(dt)
        skipped_header = True

dates = matplotlib.dates.date2num(list_of_datetimes)

fig = plt.figure(1)
#UZTWC
ax1 = fig.add_subplot(111)
plt.plot(dates, UZTWC, '-', color='b', lw=2)
ax1.fill_between(dates, 0, UZTWC)
fig.autofmt_xdate()
plt.title('UZTWC', fontsize=15)
plt.ylabel('MM', fontsize=10)
plt.tick_params(axis='both', which='major', labelsize=10)
plt.tick_params(axis='both', which='minor', labelsize=10)
plt.grid()

plt.show()

这会产生:

Traceback (most recent call last):
  File "test_color.py", line 36, in <module>
    ax1.fill_between(dates, 0, UZTWC)
  File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\__init__.py", line 1812, in inner
    return func(ax, *args, **kwargs)
  File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\site-packages\matplotlib\axes\_axes.py", line 4608, in fill_between
   y2 = ma.masked_invalid(self.convert_yunits(y2))
  File "C:\Users\rbanks\AppData\Local\Programs\Python\Python35-32\lib\site-packages\numpy\ma\core.py", line 2300, in masked_invalid
    condition = ~(np.isfinite(a))
TypeError: ufunc 'isfinite' not supported for the input types, and the inputs could not be safely coerced to any supported types according to the casting rule ''safe''

问题似乎是 fill_ Between 无法处理“numpy.ndarray”类型的日期。我是否需要将其转换为另一种数据类型才能正常工作?

编辑:经过更多测试,我发现即使在尝试使用 list_of_datetimes 并将所有日期时间转换为时间戳之后,我仍然遇到这个确切的错误,所以我开始怀疑这是否是一个类型问题毕竟。

示例数据:

%YEAR,MO,DAY,HR,PREC(MM/DT),ET(MM/DT),Q(CMS), UZTWC(MM),UZFWC(MM),LZTWC(MM),LZFPC(MM),LZFSC(MM),ADIMC(MM), ET(MM/DT)
2012,   5,   1,   0,     0.000,     1.250,     0.003,     2.928,     0.000,     3.335,     4.806,     0.000,     6.669,     1.042
2012,   5,   1,   6,     0.000,     1.250,     0.003,     2.449,     0.000,     3.156,     4.798,     0.000,     6.312,     0.987
2012,   5,   1,  12,     0.000,     1.250,     0.003,     2.048,     0.000,     2.970,     4.789,     0.000,     5.940,     0.929
2012,   5,   1,  18,     0.000,     1.250,     0.003,     1.713,     0.000,     2.782,     4.781,     0.000,     5.564,     0.869
2012,   5,   2,   0,     0.000,     1.250,     0.003,     1.433,     0.000,     2.596,     4.772,     0.000,     5.192,     0.809
2012,   5,   2,   6,     0.000,     1.250,     0.003,     1.199,     0.000,     2.414,     4.764,     0.000,     4.829,     0.750

我在 Windows 10 上使用 Python 3.5.0 和 matplotlib 1.5.1,并通过 WinPython https://sourceforge.net/projects/winpython/ 获得了所有依赖项

最佳答案

我还没有确定你的原始代码出了什么问题,但我让它与 pandas 一起工作。 :

import pandas as pd, matplotlib.pyplot as plt, matplotlib.dates as mdates

df = pd.read_csv('/path/to/yourfile.csv')
df['date'] = df['%YEAR'].astype(str)+'/'+df['MO'].astype(str)+'/'+df['DAY'].astype(str)
df['date'] = pd.to_datetime(df['date'])
dates = [date.to_pydatetime() for date in df['date']]

yyyy_mm_dd_format = mdates.DateFormatter('%Y-%m-%d')

plt.clf()
fig = plt.figure(1)
ax = fig.add_subplot(111)
ax.plot_date(dates,df[' UZTWC(MM)'],'-',color='b',lw=2)
ax.fill_between(dates,0,df[' UZTWC(MM)'])
ax.xaxis.set_major_formatter(yyyy_mm_dd_format)
ax.set_xlim(min(dates), max(dates))
fig.autofmt_xdate()
plt.show()

enter image description here

关于python - PyPlot 中 x 轴和图形之间的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38648770/

相关文章:

python - 运行 fuzzywuzzy/fuzz.py 时出错

Python 从更高/其他文件夹导入函数

python - HTML 代码中不需要的 bang(!)

python - Matplotlib hexbin : How to avoid displaying bins where np. 平均值为零

python - Matplotlib 一张图中的多种颜色

python - 使用 for 循环在 1 个图中绘制多个图

python - 根据条件在数据框中查找值

python - 如何在 OpenCV 中绘制一组闭合的多边形曲线,将每个段表示为不同的颜色(即在彩虹色空间中)?

python - 创建一个包含 pandas 中所有日期的绘图

python - 如何在 Matplotlib 动画中创建动态标题