首页 > 解决方案 > 在 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()

这是情节的错误还是我做错了什么?

标签: pandasmatplotlibplotly

解决方案


主要问题是日期值未按排序顺序显示。有必要明确地对它们进行排序。

另一个问题是“值”列中的数字与其他数字的范围完全不同。要将它们显示在同一个图中,可以添加辅助 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()

样本输出


推荐阅读