Skip to main content
 首页 » 编程设计

python之为什么 plt.figure(figsize) 在绘制 pd.DataFrame 和 pd.Series 时呈现不同的结果

2024年11月24日11mfryf

<分区>

在下面的两个片段中,唯一的区别似乎是数据源类型(pd.Series vs pd.DataFrame),plt.figure (num=None, figsize=(12, 3), dpi=80) 在使用 pd.DataFrame.plot 时在一种情况下有效但在另一种情况下无效?


片段 1 - 当数据是 pandas 系列时调整绘图大小

# Imports 
import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 
 
# data 
np.random.seed(123) 
df = pd.Series(np.random.randn(10000),index=pd.date_range('1/1/2000', periods=10000)).cumsum() 
print(type(df)) 
 
# plot 
plt.figure(num=None, figsize=(12, 3), dpi=80) 
ax = df.plot() 
plt.show() 

输出 1

片段 2 - 现在数据源是 pandas Dataframe

# imports 
import pandas as pd 
import matplotlib.pyplot as plt 
import numpy as np 
 
# data 
np.random.seed(123) 
dfx = pd.Series(np.random.randn(100),index=pd.date_range('1/1/2000', periods=100)).cumsum() 
dfy = pd.Series(np.random.randn(100),index=pd.date_range('1/1/2000', periods=100)).cumsum() 
df = pd.concat([dfx, dfy], axis = 1) 
print(type(df)) 
 
# plot 
plt.figure(num=None, figsize=(12, 3), dpi=80) 
ax = df.plot() 
plt.show() 

这里唯一的区别似乎是数据源的类型。为什么这对 matplotlib 输出有话要说?