我发现pandas
DataFrame.plot
方法非常有用,我特别喜欢它在x变量是日期时格式化x刻度的方式。但是,有时我想在使用DataFrame.plot
生成的绘图上添加更复杂的标记。例如,使用ax = my_timeseries_df.plot("date", "value)
绘制时间序列,然后对ax
对象调用fill_between
方法以添加置信区间。但是,当我在pandas
中使用一个ax
对象之后调用它的绘图方法时,我不能得到任何标记来显示。
下面是一个示例:
下面是原始代码:
import matplotlib.pyplot as plt
import pandas as pd
test = pd.DataFrame({
"a": pd.date_range(start="2020-04-21", periods=5, freq="D"),
"b": [1, 2, 3, 4, 5],
"c": [2, 4, 6, 8, 10],
})
fig, ax = plt.subplots()
test.plot("a", "b", ax=ax)
ax.plot(test.a, test.c, color="red", linewidth=20)
奇怪的是,y限制在调用ax.plot(...)
以容纳新点后发生了变化,但是新行并没有出现。
我尝试将%matplotlib inline
添加到单元格中,但没有任何帮助。我总是可以绕过DataFrame.plot
,使用matplotlib
来做任何事情,但是直接在matplotlib
中处理基于时间的x-tick已经够烦人的了,所以我很乐意让pandas
为我做这件事。
发布于 2020-06-30 21:05:34
使用x_compat=True
,请参阅文档here
import matplotlib.pyplot as plt
import pandas as pd
test = pd.DataFrame({
"a": pd.date_range(start="2020-04-21", periods=5, freq="D"),
"b": [1, 2, 3, 4, 5],
"c": [2, 4, 6, 8, 10],
})
fig, ax = plt.subplots()
test.plot("a", "b", ax=ax, x_compat=True)
ax.plot(test.a, test.c, color="red", linewidth=20)
输出:
发布于 2020-06-30 21:35:33
此外,作为参考,matplotlib
有两个类,它们可以更容易地接近pandas
内置的刻度格式:AutoDateLocator
和ConciseDateFormatter
。尽管它们仍然不能让你完全平等。你可以拿到docs here。
import matplotlib.dates as mdates
import matplotlib.pyplot as plt
import pandas as pd
test = pd.DataFrame({
"a": pd.date_range(start="2020-04-21", periods=5, freq="D"),
"b": [1, 2, 3, 4, 5],
"c": [2, 4, 6, 8, 10],
})
fig, ax = plt.subplots()
locator = mdates.AutoDateLocator(minticks=3, maxticks=10)
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.plot(test.a, test.b)
ax.plot(test.a, test.c, color="red", linewidth=2)
https://stackoverflow.com/questions/62665805
复制相似问题