ℕʘʘ*_*ḆḽḘ 14 python matplotlib pandas
考虑这个简单的例子
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.ticker import FuncFormatter
import matplotlib.dates as mdates
pd.__version__
Out[147]: u'0.22.0'
idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')
df = pd.Series(np.random.randn(len(idx)), index = idx)
df.head()
Out[145]:
2017-01-01 05:03:00 0.4361
2017-01-01 05:04:00 0.9737
2017-01-01 05:05:00 0.8430
2017-01-01 05:06:00 0.4292
2017-01-01 05:07:00 0.5739
Freq: T, dtype: float64
Run Code Online (Sandbox Code Playgroud)
我想绘制这个,并且每小时都有刻度.我用:
fig, ax = plt.subplots()
hours = mdates.HourLocator(interval = 1) #
h_fmt = mdates.DateFormatter('%H:%M:%S')
df.plot(ax = ax, color = 'black', linewidth = 0.4)
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)
Run Code Online (Sandbox Code Playgroud)
这使
为什么这里每小时都不会出现蜱虫?谢谢你的帮助!
Imp*_*est 20
问题在于,虽然大熊猫一般直接包装matplotlib绘图方法,但对于具有日期的绘图则不是这种情况.只要日期都参与其中,熊猫使用日期的一个完全不同的数字表示,因此也使用自己的定位器的刻度.
如果您想在使用matplotlib.dates
pandas创建的图上使用 格式化程序或定位器,您可以使用x_compat=True
pandas图中的选项.
df.plot(ax = ax, color = 'black', linewidth = 0.4, x_compat=True)
Run Code Online (Sandbox Code Playgroud)
这允许使用matplotlib.dates
格式化程序或定位器,如下所示.否则,你可能会取代df.plot(ax = ax, color = 'black', linewidth = 0.4)
由
ax.plot(df.index, df.values, color = 'black', linewidth = 0.4)
Run Code Online (Sandbox Code Playgroud)
完整的例子:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')
df = pd.Series(np.random.randn(len(idx)), index = idx)
fig, ax = plt.subplots()
hours = mdates.HourLocator(interval = 1)
h_fmt = mdates.DateFormatter('%H:%M:%S')
ax.plot(df.index, df.values, color = 'black', linewidth = 0.4)
#or use
df.plot(ax = ax, color = 'black', linewidth = 0.4, x_compat=True)
#Then tick and format with matplotlib:
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)
fig.autofmt_xdate()
plt.show()
Run Code Online (Sandbox Code Playgroud)
secondary_y
,matplotlib图的等效物将是双轴twinx
.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
idx = pd.date_range('2017-01-01 05:03', '2017-01-01 18:03', freq = 'min')
df = pd.DataFrame(np.cumsum(np.random.randn(len(idx), 2),0),
index = idx, columns=list("AB"))
fig, ax = plt.subplots()
ax.plot(df.index, df["A"], color = 'black')
ax2 = ax.twinx()
ax2.plot(df.index, df["B"], color = 'indigo')
hours = mdates.HourLocator(interval = 1)
h_fmt = mdates.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_locator(hours)
ax.xaxis.set_major_formatter(h_fmt)
fig.autofmt_xdate()
plt.show()
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7470 次 |
最近记录: |