个人数据分析学习公众号:genshang
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_theme(style='whitegrid',palette='deep')
# 读取标普500指数和富时100指数数据
df_spx500_and_ftse100 = pd.read_csv('line_chart_data.csv')
# 预览数据样式
df_spx500_and_ftse100.head(5)
# 此时的Date列为字符串,由于下面需要进行日期比较,所以需要将字符格式转为datetime格式
# 数据处理:字符 >> 日期格式(通过pd.to_datetime()实现)
df_spx500_and_ftse100['Date'] = pd.to_datetime(df_spx500_and_ftse100['Date'])
# 预览格式转换后的结果
df_spx500_and_ftse100.head(5)
# 设置过滤条件:只显示2010年的指数数据
year_2010 = (df_spx500_and_ftse100['Date']>='2010-01-01') & (df_spx500_and_ftse100['Date']<='2010-12-31')
# 生成仅包含2010年数据的新的DataFrame
df_spx500_and_ftse100_in_2010 = df_spx500_and_ftse100[year_2010]
# 保证日期升序没错
df_spx500_and_ftse100_in_2010.sort_values(by='Date',inplace=True)
# 预览效果
df_spx500_and_ftse100_in_2010.head(10)
legend_labels = ['GSPC500','FTSE100']
plt.figure(figsize=(20,10))
# 分别绘制两条线
plt.plot(df_spx500_and_ftse100_in_2010['Date'],df_spx500_and_ftse100_in_2010['GSPC500'])
plt.plot(df_spx500_and_ftse100_in_2010['Date'],df_spx500_and_ftse100_in_2010['FTSE100'])
# 设置标题
plt.title('S&P 500 & FTSE 100',fontsize=24, fontweight = 'bold')
# 设置图例
plt.legend(labels = legend_labels, loc='best', fontsize=18)
plt.show()
import datetime
from dateutil.relativedelta import relativedelta
# 生成X轴刻度:每月1号组成的list
month_1_list = [datetime.date(2010,1,1)]
for i in range(1,12):
month_1_list.append(datetime.date(2010,1,1) + relativedelta(months=+i))
month_1_list.append(datetime.date(2010,12,31))
# -------------------------------------------------
legend_labels = ['GSPC500','FTSE100']
plt.figure(figsize=(20,10))
plt.plot(df_spx500_and_ftse100_in_2010['Date'],df_spx500_and_ftse100_in_2010['GSPC500'],linewidth=2)
plt.plot(df_spx500_and_ftse100_in_2010['Date'],df_spx500_and_ftse100_in_2010['FTSE100'],linewidth=2)
# 自定义X轴刻度:为每月月初(若未特殊指定,则会默认生成轴刻度)
plt.xticks(ticks=month_1_list,rotation=40,fontsize=14)
plt.yticks(fontsize=14)
plt.title('S&P 500 & FTSE 100',fontsize=24, fontweight = 'bold')
plt.legend(labels = legend_labels, loc='best', fontsize=16)
plt.show()