Python学习之-数据处理-数据可视化 第1关:绘制子图
【摘要】 #coding=utf-8import pandas as pdimport matplotlib.pyplot as pltimport timedef create_aveg_open(stock_code): quotesdf_ori = pd.read_csv('step1/'+stock_code+'.csv', index_col=[0]) ###### Be...
#coding=utf-8
import pandas as pd
import matplotlib.pyplot as plt
import time
def create_aveg_open(stock_code):
quotesdf_ori = pd.read_csv('step1/'+stock_code+'.csv', index_col=[0])
###### Begin ######
# 将索引转换为日期时间格式
quotesdf_ori.index = pd.to_datetime(quotesdf_ori.index)
# 按月份分组并计算每月开盘价的平均值(使用小写的'open'列名)
quotesdf_ori['year_month'] = quotesdf_ori.index.to_period('M')
monthly_avg = quotesdf_ori.groupby('year_month')['open'].mean() # 已修正为小写
meanopen = monthly_avg.values
###### End ######
return meanopen
def plot():
open1 = create_aveg_open('INTC') # Intel的每月平均开盘价
open2 = create_aveg_open('IBM') # IBM的每月平均开盘价
plt.figure(figsize=(10,10), dpi=100)
###### Begin ######
# 创建子图
ax = plt.subplot(111)
# 生成x轴数据(月份)
months = range(1, len(open1) + 1)
# 绘制Intel数据,使用圆形标记
ax.plot(months, open1, 'o-', color='blue', label='INTC')
# 绘制IBM数据,使用圆形标记
ax.plot(months, open2, 'o-', color='red', label='IBM')
# 添加标题和轴标签
ax.set_title('Monthly Average Opening Price')
ax.set_xlabel('Month')
ax.set_ylabel('Average Opening Price')
# 添加图例
ax.legend()
# 设置x轴刻度
ax.set_xticks(months)
###### End ######
plt.show()
plt.savefig('step1/outfile/sub.png')
plt.close()
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)