Matplotlib绘图基础之折线图(标普500和富时100指数分析)

import pandas as pd
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()

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值