简体   繁体   中英

The data in the 2nd plot in vertically stacked Plotly sub-plot not being displayed correctly in Django 3.1 app

I am running a Django 3.1 app using plotly to display an interactive chart in a.html template file.

I am trying to create a plot using the subplots functionality.

The plot has 2 rows and 1 column. The first row correctly displays the first chart which is a Candlestick plot of daily stock prices. The second row of the plot was to be a bar chart of the volume for each of the days of the stock price.

When I run the app, I receive no server errors and the.html page loads as expected.

However, the second plot should be a bar chart of the volume but the chart is blank. The plot correctly displays the yaxis and xaxis title and values for the tick as expected for the Volume data.

If I set the axis_rangeslider_visible to True, then the chart displays the rangeselector in the 2nd chart where the volume data should be. The axis labels still display the expected values and labels as if the volume data is plotted.

The following code is from my views.py file within the Django app.

from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin
from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView
from users.models import CustomUser
from .models import Chart

import pandas as pd
from datetime import datetime
from smart_open import smart_open
from django.conf import settings
import plotly.express as px
import plotly.graph_objs as go
from plotly.subplots import make_subplots


class ChartDetailView(LoginRequiredMixin, DetailView):
    model = Chart
    
    def get_queryset(self):
        return Chart.objects.filter(user=self.request.user)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        
        path = 's3://{}:{}@{}/{}'.format(settings.AWS_ACCESS_KEY_ID,
                                         settings.AWS_SECRET_ACCESS_KEY,
                                         settings.AWS_STORAGE_BUCKET_NAME,
                                         self.object.data_file.name)

        df_daily = pd.read_csv(smart_open(path), parse_dates=True)
        df_daily['Date'] = pd.to_datetime(df_daily['Date'])
        df_daily = df_daily.set_index('Date')

        fig_daily = make_subplots(rows=2, cols=1,
                                 row_heights=[0.8, 0.2],
                                 specs=[[{"type": "candlestick"}],
                                        [{"type": "bar"}]],
                                 shared_xaxes=True,
                                 vertical_spacing=0.02)

        fig_daily.add_trace(go.Candlestick(x=df_daily.index,
                                           open=df_daily['Open'],
                                           high=df_daily['High'],
                                           low=df_daily['Low'],
                                           close=df_daily['Close'],
                                           showlegend=False,
                                           ),
                            row=1, col=1)

        fig_daily.add_trace(go.Bar(x=df_daily.index,
                                   y=df_daily['Volume'],
                                   marker=dict(color="crimson"),
                                   showlegend=False),
                            row=2, col=1)

        # Update xaxis properties
        fig_daily.update_xaxes(title=None,row=1, col=1)
        fig_daily.update_xaxes(title="Date", row=2, col=1)

        # Update yaxis properties
        fig_daily.update_yaxes(title="$/share", row=1, col=1)
        fig_daily.update_yaxes(title="Volume", range=[0, df_daily['Volume'].max()], row=2, col=1)

        fig_daily.update_layout(title='Daily Stock Price and Volume',
                                xaxis_rangeslider_visible=False,
                                margin=dict(r=5, t=30, b=5, l=5),
                                height=650,
                                width=700)

        graph_daily = fig_daily.to_html()

        df_daily = df_daily[['Open', 'High', 'Low', 'Close', 'Volume']].to_html(classes='mystyle')

        context['df_daily'] = df_daily
        context['graph_daily'] = graph_daily

        return context

Well I still don't understand what the underlying problem is. However I have resolved my immediate need by plotting a smaller sample size. The original plot had about 5,500 data points. When I restricted the size to less than 500, the second subplot displayed correctly.

So is there an upper limit on how many data points can be used in plotly sub plots. And only in the second plot. Puzzling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM