Skip to content

[MPL conversion] Offline plot does not show legend correctly #910

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
onewhaleid opened this issue Jan 6, 2018 · 7 comments
Closed

[MPL conversion] Offline plot does not show legend correctly #910

onewhaleid opened this issue Jan 6, 2018 · 7 comments

Comments

@onewhaleid
Copy link

onewhaleid commented Jan 6, 2018

Using plotly.offline.plot_mpl, I am not able to create an interactive legend. In fact, the legend entries simply appear as text, without the matching line or symbol key.

plotly 2.2.2
matplotlib 2.1.0

Here is my code:

import matplotlib.pyplot as plt
import plotly.offline

fig, ax = plt.subplots()

ax.plot([0, 1, 2], [0, 1, 2], 'o-', label='a')
ax.plot([0, 1, 2], [0.5, 1.5, 2.5], 'o-', label='b')

ax.legend()

plotly.offline.plot_mpl(fig, filename='temp-plot.html')

image

@zeruitle
Copy link

zeruitle commented Jan 11, 2018

Oops, sorry I think we have different problem.

If you use figure, I believe you need show_colorbar=True to use legend?

my situation is I have legend on my plot, but the toggle simply not working

image

########################################
Similar situation, but I suspected not because offline?

situation 1: all gantt example can't toggle legend
https://plot.ly/python/gantt/#using-hours-and-minutes-in-times

situation 2: I tried my own offline gantt, can't toggle

situation 3: tried other offline example, it can toggle
https://plot.ly/python/offline/#plotting-offline-with-cufflinks

anyway, just want my offline gantt can toggle legend...

fig = ff.create_gantt(df, colors=colors, index_col='Resource', title='Daily Schedule',
                      show_colorbar=True, bar_width=0.8, showgrid_x=True, showgrid_y=True, group_tasks=True)

plotly.offline.plot(fig, filename='gantt-hours-minutes.html')

@astrojuanlu
Copy link
Contributor

my situation is I have legend on my plot, but the toggle simply not working

I reported a separate issue #1371 so this can stay focused on the plot_mpl issue.

@pshassett
Copy link

pshassett commented Jun 12, 2019

Getting same issue using pandas plot method:

import matplotlib.pyplot as plt
import plotly
import pandas as pd

time = range(20)
y1 = []
y2 = []
for i in time:
    y1.append(i**1.5)
    y2.append(i**2)
data = {'y1': y1,
        'y2': y2}
df = pd.DataFrame(data)

fig = plt.figure(figsize=(9, 5))
ax = fig.gca()
df.plot(legend=True, ax=ax)
ax.set_xlabel('x-label')
ax.set_ylabel('y-label')
lgd = plt.legend(loc='lower right', shadow=True, title='legend', fancybox=True)
lgd.get_frame().set_alpha(0.5)
plt.show()
plotly.offline.plot_mpl(fig, filename='./plt_fig.html', auto_open=False)

plotly

@avivajpeyi
Copy link

avivajpeyi commented Nov 26, 2019

Getting the same issue... It has almost been 2 yrs since this was opened. Any updates/suggestions?

Code to reproduce

$ pip install bilby
from __future__ import division, print_function

import bilby 
import matplotlib.pyplot as plt
import plotly
import plotly.tools as tls
import plotly.graph_objects as go
from matplotlib.ticker import (AutoMinorLocator)

approximants = ["IMRPhenomPv2", "SEOBNRv4"]

injection_parameters = dict(
    mass_1=141.0741,
    mass_2=113.0013,
    a_1=0.9434,
    a_2=0.2173,
    tilt_1=0,
    tilt_2=0,
    phi_jl=0,
    phi_12=0,
    luminosity_distance=1782.1610,
    theta_jn=0.9614,
    psi=1.6831,
    phase=5.2220,
    geocent_time=1242424473.5880,
    ra=0.9978,
    dec=-0.4476
)


def get_data(approximants, injection_parameters):
    generator_args = dict(
        duration=4,
        sampling_frequency=2048.,
        frequency_domain_source_model=bilby.gw.source.lal_binary_black_hole,
        parameters=injection_parameters
    )

    waveform_args = dict(reference_frequency=50.)

    approximant_data = dict()
    for approximant in approximants:
        waveform_args.update(dict(waveform_approximant=approximant))
        generator_args.update(waveform_arguments=waveform_args)
        generator = bilby.gw.WaveformGenerator(**generator_args)
        h_signal = generator.time_domain_strain(injection_parameters)
        h_time = generator.time_array
        approximant_data.update({approximant: dict(x=h_time, y=h_signal['plus'])})
    return approximant_data


def matplot_plot_data(approximant_data):
    fig, ax = plt.subplots()

    for approximant, data in approximant_data.items():
        ax.plot(data['x'], data['y'], label=approximant)

    ax.xaxis.set_minor_locator(AutoMinorLocator())
    ax.set_title('Comparing Time-Domain Data')
    ax.set_ylabel('Strain')
    ax.set_xlabel('Time (s)')
    ax.legend()
    return fig


def plotly_plot_data(fig):
    plotly_fig = tls.mpl_to_plotly(fig)
    plotly.offline.plot(plotly_fig, filename="plotly_strain.html")


data = get_data(approximants, injection_parameters)
fig = matplot_plot_data(data)
plotly_plot_data(fig)

Matplotlib Plot:

Screen Shot 2019-11-26 at 4 15 31 pm

Plotly Plot:

Screen Shot 2019-11-26 at 4 15 40 pm

@avivajpeyi
Copy link

I came up with a hack-y fix which does the job:

def plotly_plot_data(fig):
    ax_list = fig.axes
    for ax in ax_list:
        ax.get_legend().remove()

    plotly_fig = tls.mpl_to_plotly(fig)
    legend = go.layout.Legend(
        x=0.05,
        y=0.95
    )
    plotly_fig.update_layout(showlegend=True, legend=legend)
    plotly.offline.plot(plotly_fig, filename="plotly_strain.html")

Screen Shot 2019-11-26 at 4 57 37 pm

@nicolaskruchten
Copy link
Contributor

We're not really maintaining the matplotlib-to-plotly conversion pipeline ourselves very much these days (although we would be happy to review and accept pull requests to it!) so the approach proposed immediately-above is probably the best way forward today.

@nicolaskruchten nicolaskruchten changed the title Offline plot does not show legend correctly [MPL conversion] Offline plot does not show legend correctly Nov 26, 2019
@gvwilson
Copy link
Contributor

Hi - this issue has been sitting for a while, so as part of our effort to tidy up our public repositories I'm going to close it. If it's still a concern, we'd be grateful if you could open a new issue (with a short reproducible example if appropriate) so that we can add it to our stack. Cheers - @gvwilson

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

8 participants