Легенды в PLOTLY и mpl_to_plotly имеют разные метки. - PullRequest
0 голосов
/ 05 августа 2020

Вот код для линейной диаграммы и гистограмм объема на вторичной оси. Он правильно отображается в plt.show (). Но когда он конвертируется с помощью mpl_to_plotly, легенды не появляются правильно ... Мне нужны легенды:

  • Цена закрытия
  • Увеличение объема
  • Снижение объема

Но я получаю

  • Цена закрытия

  • Трассировка 1

  • Trace 2

      fig = plt.figure()
      fig.set_size_inches((16, 8))
      ax = fig.add_axes((0.06, 0.25, 0.85, 0.70))
      ax2 = fig.add_axes((0.06, 0.04, 0.85, 0.13), sharex=ax) #secondary axis. 
      ax.set_ylabel('Price')
      ax2.yaxis.set_label_position("right")
      ax2.set_ylabel('Volume', size=20)
    
      #ax.set_ylim(df['Close Price'].min, df['Close Price'].max)
      ln1= ax.plot_date(df['Date_Week'], df['Close Price'], ls="-", label='Close Price') #closeprice
      #ln2 = ax.plot_date(df2['Date_Week'], df2['line1'],  color='firebrick', ls="--",lw=2.0, label='Avg. Support' ) #avg support
      #ln3 = ax.plot_date(df4['Date_Week'], df4['line1'],color="black", ls="--",lw=2.0, label='Avg. Resistance') #avg resistance
      #ln4 = ax.plot_date(df5['Date_Week'], df5['line1'],color="green", ls="-.",lw=2.0, label='Support') # support
      #ln5 = ax.plot_date(df7['Date_Week'], df7['line1'],color="red", ls="-.",lw=2.0, label='Resistance') #resistance
    
      ax.tick_params('y', colors='k')
      ax.grid(b=True, which='major', color='w', linewidth=1.0)
      ax.grid(b=True, which='minor', color='w', linewidth=0.5)
      ax.yaxis.grid(True)
      ax.margins(0.1, None)    
      pos = hist[i:].Open-hist[i:].Close<0
      neg = hist[i:].Open-hist[i:].Close>0
      datedf.dropna(subset = ['Date_Week'],inplace=True)
      volumelabel=['Up Volume','Down Volume']
    

    гистограмма объема на вторичной оси.

      lnup = ax2.bar(hist[i:][pos].index,v[pos],color='green',width=1,align='center')
      lndown= ax2.bar(hist[i:][neg].index,v[neg],color='red',width=1,align='center')
      ax2.legend(volumelabel,loc=2)
      print("finished")
      #print(ax1.legend)
      #quit()
      #scale the x-axis tight
      ax2.set_xlim(min(hist[i:].index)- datetime.timedelta(days=4),max(hist[i:].index)+ datetime.timedelta(days=4))
      # the y-ticks for the bar were too dense, keep only every third one
      yticks = ax2.get_yticks()
      #ax2.set_yticks(yticks[::1])
    
      # the y-ticks for the bar were too dense, keep only every third one
      yticks = ax2.get_yticks()
      #ax2.set_yticks(yticks[::3])
    
      # format the x-ticks with a human-readable date.
      xt = ax2.get_xticks()
      new_xticks = [datetime.date.isoformat(num2date(d)) for d in xt]
      ax.set_xticklabels(new_xticks)
      ax2.yaxis.set_label_position("right")
      ax2.set_ylabel('Volume', size=20)
    
      # added these three lines
      #lns = ln1+ln2+ln3+ln4+ln5+[lnup]+[lndown]
      #lns = ln1+ln2+ln3+ln4+ln5
      lns = ln1+[lnup]+[lndown]
      labs = [l.get_label() for l in lns]
      ax.legend(lns, labs, loc=2)              
      plt.show()
      ax.get_legend().remove()
      #ax2.get_legend().remove()
    
      myFmt = mdates.DateFormatter('%Y-%m-%d')
      ax.xaxis.set_major_formatter(myFmt)
      fig.autofmt_xdate()
      plotly_fig = tls.mpl_to_plotly(fig)
    
      #### converted to mpl_to_plotly ##### 
      myFmt = mdates.DateFormatter('%Y-%m-%d')
      ax.xaxis.set_major_formatter(myFmt)
      fig.autofmt_xdate()
      plotly_fig = tls.mpl_to_plotly(fig)
      #plotly_fig['layout']['plot_bgcolor'] = "rgb(213, 226, 233)"
      #plotly_fig['layout']['xaxis']['gridcolor'] = "white"
      #plotly_fig['layout']['yaxis']['gridcolor'] = "white"
      #plotly_fig['layout']['xaxis']['ticks'] = ""
      #plotly_fig['layout']['yaxis']['range'] = limits
      #plotly_fig['layout']['yaxis']['title'] = ylabel
      #plotly_fig['layout']['autosize'] = True
      #plotly_fig['layout']['showlegend'] = True
      #plotly_fig['layout']['title'] = 'Trend Lines'+sym
    
    
      legend = go.layout.Legend(
              x=0.05,
              y=0.95
          )
      title = go.layout.Title(
              x=0.5,
              y=0.93
          )
      plotly_fig.update_layout(showlegend=True, legend=legend)
      plotly_fig.update_layout(
          title=title,
          title_text='Trendlines',
          titlefont = {'size':18}
      )
      #plotly_fig.for_each_annotation(lambda a: a.update(text=a.text.split("trace")[-1]))
      #plotly_fig.update_layout(uniformtext_minsize=12, uniformtext_mode='hide')
      plotly.offline.plot(plotly_fig, filename=sym+".html")
    

На диаграмме matplot (plt.show ()) легенда отображается правильно. Но в plotly_fig легенда неверна для гистограмм ..... Это, похоже, происходит с диаграммами со вторичной осью с гистограммами при преобразовании в mpl_to_plot

изображение plt.show () отображается первым ниже. [enter image description here 1

Изображение MPL_TO_PLOT на странице html показано ниже:

введите описание изображения здесь

Обратите внимание, как метки для гистограмм добавляются как «Кривая 1» и «Трассировка 2». Метка правильно подходит для линии, но для столбчатой ​​диаграммы объема во вспомогательной диаграмме на вторичной оси она отображается как трассировка 1 и трасса 2. Мне нужен способ получить доступ к легенде и обновить ее местоположение, а также изменить ее с трассы 1 на увеличение объема и трассы 2 на уменьшение объема.

Как мне обновить или отредактировать метки в легенде в mpl_to_plotly цифра в html

...