0

I'm a beginner in the world of python programming and I'm having a really hard time figuring out how to tackle my problem.

The problem is when I created a plot using loop in python with matplotlib and mpld3, the plot is as I expected it to be but the legend of the plot is really wrong because the legends were overlapping with each other. The legend of the plot will be displayed for the latest data only because other data's legend is overlapped on it.

Below is the picture of my plot:

Image

This is the code to create the plot and legend in loop:

plt.rcParams.update({'font.size': 13})
fig, ax = plt.subplots()
for i in range(3,5):
        rd1 = pd.read_sql_query("SELECT press, rs FROM basic_chart WHERE 
        cs = "+str(i), app.config['SQLALCHEMY_DATABASE_URI'])
        print(rd1)
        pt = ax.plot(rd1['press'],rd1['rs'],'-o')
        plugins.connect(fig, plugins.InteractiveLegendPlugin([pt],[str(i)]))
html = mpld3.fig_to_html(fig)

I think that the main problem is on the interactive legend code but I did not manage to figure out the right way to correct it. I really hope experts can help me in this problem.

tmdavison
  • 64,360
  • 12
  • 187
  • 165
izz
  • 11
  • 7
  • I haven't ever used `mpld3`, so I'm not sure, but you might try moving the `InteractiveLegendPlugin` line outside of your `for` loop. You could append `pt` and `str(i)` to some lists, and feed them to the legend plugin in one go. – tmdavison Sep 05 '17 at 14:49
  • mpld3 is actually used to embed matplotlib into web page, thanks for the advice i'll give it some thought. – izz Sep 05 '17 at 14:56
  • not helpful actually – izz Sep 06 '17 at 09:34

1 Answers1

0
plt.rcParams.update({'font.size': 13})
fig, ax = plt.subplots()
for i in range(3,5):
    rd1 = pd.read_sql_query("SELECT press, rs FROM basic_chart WHERE 
    cs = "+str(i), app.config['SQLALCHEMY_DATABASE_URI'])
    print(rd1)
    pt = ax.plot(rd1['press'],rd1['rs'],'-o')

axhandles, axlabels = ax.get_legend_handles_labels()
plugins.connect(fig, plugins.InteractiveLegendPlugin(axhandles, axlabels))
html = mpld3.fig_to_html(fig)

By having the plugins.connect in the loop, you are creating two separate legends. After plotting, get the handles and labels from the plot and use that in the call to the InteractiveLegendPlugin.

GeorgeLPerkins
  • 1,126
  • 10
  • 24