pandas - 在 matplotlib 执行的地方无法正确加载图表
问题描述
使用 plotly 时,我确实得到了这张图片,图中有一些直线。使用 matplotlib 时我没有相同的情况。
import pandas as pd
import numpy as np
import cufflinks as cf
from plotly.offline import plot
from datetime import datetime
import io
import requests
df = cf.datagen.lines()
src = "https://iss.moex.com/iss/engines/stock/markets/index/securities/RTSI/candles.csv?iss.only=history&interval=31&iss.reverse=true&from=1995-09-01&till=2019-12-28&iss.json=extended&callback=JSON_CALLBACK&lang=en&limit=100&start=0&sort_order=TRADEDATE&sort_order_desc=desc&_=1563185736134'"
r = requests.get(src)
df = pd.read_csv(io.StringIO(r.content.decode('utf-8')),
sep=';',
names=[
'Open', 'Close', 'High', 'Low', 'Value',
'Volume', 'Date', 'End'
]).iloc[2:]
frame = {
'Date': df['Date'].astype(np.datetime64),
'Open': df['Open'].astype('float64'),
'Close': df['Close'].astype('float64'),
'High': df['High'].astype('float64'),
'Low': df['Low'].astype('float64'),
'Value': df['Value'].astype('float64'),
'Volume': df['Volume'].astype('float64'),
}
df = pd.DataFrame(frame)
plot([{
'x': df['Date'],
'y': df[col],
'name': col
} for col in df.columns[1:]])
df.iplot()
这是情节的错误还是我做错了什么?
解决方案
主要问题是日期值未按排序顺序显示。有必要明确地对它们进行排序。
另一个问题是“值”列中的数字与其他数字的范围完全不同。要将它们显示在同一个图中,可以添加辅助 y-axis。
由于未填写“音量”列(仅包含零),因此可以省略。
plotly
这是一些示例代码,跳过了最新版本可能不需要的转换步骤:
import plotly.graph_objects as go
import pandas as pd
src = "https://...."
df = pd.read_csv(src,
sep=';',
names=[
'Open', 'Close', 'High', 'Low', 'Value',
'Volume', 'Date', 'End'
]).iloc[2:]
df = df.sort_values(by='Date')
for col in df.columns:
print(col, df[col].min(), df[col].max())
fig = go.Figure()
for col in ['Open', 'Close', 'High', 'Low', 'Value']:
fig.add_trace(
go.Scatter(
x=df['Date'],
y=df[col],
name=col,
yaxis='y1' if col == 'Value' else 'y2'
))
fig.update_layout(
yaxis=dict(
title="Price",
),
yaxis2=dict(
title="Volume",
anchor="x",
overlaying="y",
side="right"
))
fig.show()
推荐阅读
- react-native - 导航到相同数据结构中的当前屏幕
- apache - 根据名称而不是扩展名添加 mime 类型
- machine-learning - 将机器学习应用于训练数据参数
- sql-server - 组合使用相似主键的两个源表时的自然键
- mysql - 加入不求和 CASE WHEN
- odoo - Qweb odoo 10 中的表格大小、thead 和 tbody
- json - 嵌套对象中的 OpenApi 必需属性不起作用
- angular - 刷新浏览器 Angular 应用程序不工作。当我将应用程序部署到 apache tomcat 时出现 404 错误
- javascript - 使用Javascript将图像拖到div上时如何缩放鬼图像?
- rest - 允许使用 3rd 方 API 从我在 Golang 中的 REST 端点下载文件