Reputation: 6171
I can plot data from a CSV file with the following code:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('test0.csv',delimiter='; ', engine='python')
df.plot(x='Column1', y='Column3')
plt.show()
But I don't understand one thing. How plt.show()
knows about df
? I'll make more sense to me seeing, somewhere, an expression like:
plt = something(df)
I have to mention I'm just learning Python.
Upvotes: 2
Views: 56
Reputation: 880429
Matplotlib has two "interfaces": a Matlab-style interface and an object-oriented interface.
Plotting with the Matlab-style interface looks like this:
import matplotlib.pyplot as plt
plt.plot(x, y)
plt.show()
The call to plt.plot
implicitly creates a figure and an axes on which to draw.
The call to plt.show
displays all figures.
Pandas is supporting the Matlab-style interface by implicitly creating a figure and axes for you when df.plot(x='Column1', y='Column3')
is called.
Pandas can also use the more flexible object-oriented interface, in which case your code would look like this:
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv('test0.csv',delimiter='; ', engine='python')
fig, ax = plt.subplots()
df.plot(ax=ax, x='Column1', y='Column3')
plt.show()
Here the axes, ax
, is explicitly created and passed to df.plot
, which then
calls ax.plot
under the hood.
One case where the object-oriented interface is useful is when you wish to use
df.plot
more than once while still drawing on the same axes:
fig, ax = plt.subplots()
df.plot(ax=ax, x='Column1', y='Column3')
df2.plot(ax=ax, x='Column2', y='Column4')
plt.show()
Upvotes: 3
Reputation: 78564
From the pandas docs on plotting:
The
plot
method on Series and DataFrame is just a simple wrapper around :meth:plt.plot() <matplotlib.axes.Axes.plot>
So as is, the df.plot
method is an highlevel call to plt.plot
(using a wrapper), and thereafter, calling plt.show
will simply:
display all figures and block until the figures have been closed
as it would with for all figures plotted with plt.plot
.
Therefore, you don't see plt = something(df)
as you would expect, because matpotlib.pyplot.plot
is being called behind the scene by df.plot
.
Upvotes: 2
Reputation: 955
According to http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.show , the plt.show()
itself doesn't know about the data, you need to pass the data as parameters.
What you are seeing should be the plot of pandas library, according to the usage http://pandas.pydata.org/pandas-docs/stable/visualization.html#basic-plotting-plot.
Hope this solves your question.
Upvotes: 1