首页 > 解决方案 > 我想在 2 个日期的同一点绘制数据

问题描述

我写了代码

test ='test.csv'
test = pd.read_csv(test)

test1 =‘test1.csv'
test1 = pd.read_csv(test1)

测试显示

Date                Score
2010-01-01             20    
2010-01-02            30
2010-01-03            40
2010-01-04            50

测试1显示

Date            Score
2010-01-01        10    
2010-01-03        40
2010-01-04       30
2010-01-10        60

我写了代码,

    import matplotlib.pyplot as plt
    import numpy as np
    import pandas as pd
    import plotly
    import plotly.graph_objs as go
    import datetime

    import plotly.offline as offline
    plotly.offline.init_notebook_mode(connected=False)

    test ='test.csv'
    test = pd.read_csv(test)
    test =test["Score"]

    test1 ="test1.csv"
    test1 = pd.read_csv(test1)
    test1 =test1["Score"]

    data = [
            plotly.graph_objs.Scatter(y = test, mode = 'lines', name = 'TEST'),
            plotly.graph_objs.Scatter(y = test1, mode = 'lines', name = 'TEST2', yaxis='y2'),
        ]

    layout = plotly.graph_objs.Layout(
        title="test",
        xaxis={"title":"test"},
        yaxis={"title":"test1"},
        yaxis2={"title":"test2", "overlaying":"y", "side":"right"},
        )

        fig = plotly.graph_objs.Figure(data=data, layout=layout)
        plotly.offline.iplot(fig)

我想在同一个 x 轴上绘制 test & test1 数据具有相同的日期。例如,test 的 2010-01-01 的 20 和 test1 的 2010-01-01 的 10 将绘制在同一个 x 轴上。所以,如果日期因缺少而暂停数据,可以只绘制圆,但可以绘制折线图。我该怎么做?我的代码有什么问题?

标签: pythonpandasplotly

解决方案


问题出在 中data,检查以下内容以获得双 y 轴的结果输出,test如下test1所示:

test['Date'] = pd.to_datetime(test['Date'])
test
Date    Score
0   2010-01-01  20
1   2010-01-02  30
2   2010-01-03  40
3   2010-01-04  50

test1['Date'] = pd.to_datetime(test1['Date'])
test1
    Date    Score
0   2010-01-01  10
1   2010-01-03  40
2   2010-01-04  30
3   2010-01-10  60

import plotly
import plotly.graph_objs as go
import datetime

import plotly.offline as offline
plotly.offline.init_notebook_mode(connected=False)

data = [go.Scatter(x = test.Date , y = test.Score , mode = 'lines', name = 'TEST'),
        go.Scatter(x = test1.Date, y = test1.Score, mode = 'lines', name = 'TEST2', 
                   yaxis='y2')]
layout = go.Layout(title="test",
                   xaxis={"title":"test"},
                   yaxis={"title":"test1"},
                   yaxis2={"title":"test2", "overlaying":"y", "side":"right"})

fig = plotly.graph_objs.Figure(data=data, layout=layout)
plotly.offline.plot(fig)

图表看起来像这样

在此处输入图像描述


推荐阅读