简体   繁体   中英

How to make a plot interactive in python Matplotlib

The data looks like this:

    Id  Timestamp               Data    Group
0   1   2013-08-12 10:29:19.673 40.0    1
1   2   2013-08-13 10:29:20.687 50.0    2
2   3   2013-09-14 10:29:20.687 40.0    3
3   4   2013-10-14 10:29:20.687 30.0    4
4   5   2013-11-15 10:29:20.687 50.0    5
                    ...

I was able to plot a normal line graph but want to create an interactive graph using Matplotlib. I used the code:

%matplotlib notebook
%matplotlib inline

df['Timestamp'] = pd.to_datetime(df['Timestamp'])   
df1 = df[df['Group'] ==1]
plt.plot( x = 'Timestamp', y = 'Data',figsize=(20, 10))
plt.show()

It returned an empty graph and error

TypeError: plot got an unexpected keyword argument 'x'

What is wrong?

Update:
Complete Error

TypeError                                 Traceback (most recent call last)
<ipython-input-33-0eb3ff7c9c6c> in <module>()
      9 df1 = df[df['Group'] ==1]
     10 # df1 = df.groupby(df['Group'])
---> 11 plt.plot( x = df1['Timestamp'], y = df1['Data'], figsize=(20, 10))

2 frames
/usr/local/lib/python3.6/dist-packages/matplotlib/axes/_base.py in __call__(self, *args, **kwargs)
    169             if pos_only in kwargs:
    170                 raise TypeError("{} got an unexpected keyword argument {!r}"
--> 171                                 .format(self.command, pos_only))
    172 
    173         if not args:

TypeError: plot got an unexpected keyword argument 'x'

EDIT: It is solution for error message, not explanation how to create interactive plot which would need event handling (Doc: Interactive plot )


To use x= you would have to use df.plot() instead of plt.plot()

df.plot(x='Timestamp', y='Data', figsize=(20, 10))

If you want to use plt.plot() then you have to sets values without x=

plt.plot(df['Timestamp'], df['Data'])

because it get it as positional arguments ( *args ), not named arguments.

And it doesn't have argument figsize=

See arguments in documentation matplotlib.pyplot.plot()

As advised by @GIRISHkuniyal, using plotly.express helps to make the plot interactive with code:

import plotly.express as px
fig = px.line(df1, 'Timestamp', 'Data')
fig.show()

Thanks


Update: Sometimes may have to run

def configure_plotly_browser_state():
  import IPython
  display(IPython.core.display.HTML('''
        <script src="/static/components/requirejs/require.js"></script>
        <script>
          requirejs.config({
            paths: {
              base: '/static/base',
              plotly: 'https://cdn.plot.ly/plotly-latest.min.js?noext',
            },
          });
        </script>
        '''))

beforehand as explained in this answer to custom initialise Plotly.

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