Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 7ac93a0

Browse files
committed
More explanation on plotting data from files
1 parent b1141fd commit 7ac93a0

File tree

1 file changed

+97
-16
lines changed

1 file changed

+97
-16
lines changed

examples/misc/plotfile_demo_sgskip.py

Lines changed: 97 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,86 +1,167 @@
11
"""
2-
=============
3-
plotfile demo
4-
=============
2+
=========================
3+
Plotting data from a file
4+
=========================
55
6-
Replacing the deprecated `plotfile` by pandas or other matplotlib plotting
7-
methods.
6+
Plotting data from a file is actually a two-step process.
7+
8+
1. Interpreting the file and loading the data.
9+
2. Creating the actual plot.
10+
11+
`.pyplot.plotfile` tried to do both at once. But each of the steps has so many
12+
possible variations and parameters that it does not make sense to squeeze both
13+
into a single function. Therefore, `.pyplot.plotfile` has been deprecated.
14+
15+
The recommended way of plotting data from a file is therefore to use dedicated
16+
functions such as `numpy.loadtxt` or `pandas.read_csv` to read the data. These
17+
are more powerful and faster. Then plot the obtained data using matplotlib.
18+
19+
Note that `pandas.DataFrame.plot` is a convenient wrapper around Matplotlib
20+
to create simple plots.
821
"""
922

1023
import matplotlib.pyplot as plt
1124
import matplotlib.cbook as cbook
1225

1326
import numpy as np
1427
import pandas as pd
15-
pd.plotting.register_matplotlib_converters()
1628

17-
# Time series.
29+
###############################################################################
30+
# Using pandas
31+
# ============
32+
#
33+
# Subsequent are a few examples of how to replace `~.pyplot.plotfile` with
34+
# `pandas`. All examples need the the `pandas.read_csv` call first. Note that
35+
# you can use the filename directly as a parameter::
36+
#
37+
# msft = pd.read_csv('msft.csv')
38+
#
39+
# The following slightly more involved `pandas.read_csv` call is only to make
40+
# automatic rendering of the example work:
41+
1842
fname = cbook.get_sample_data('msft.csv', asfileobj=False)
43+
with cbook.get_sample_data('msft.csv') as file:
44+
msft = pd.read_csv(file)
45+
46+
###############################################################################
47+
# When working with dates, additionally call
48+
# `pandas.plotting.register_matplotlib_converters` and use the ``parse_dates``
49+
# argument of `pandas.read_csv`::
50+
51+
pd.plotting.register_matplotlib_converters()
52+
1953
with cbook.get_sample_data('msft.csv') as file:
2054
msft = pd.read_csv(file, parse_dates=['Date'])
2155

22-
# Use indices.
56+
57+
###############################################################################
58+
# Use indices
59+
# -----------
60+
61+
# Deprecated:
2362
plt.plotfile(fname, (0, 5, 6))
2463

64+
# Use instead:
2565
msft.plot(0, [5, 6], subplots=True)
2666

27-
# Use names.
67+
###############################################################################
68+
# Use names
69+
# ---------
70+
71+
# Deprecated:
2872
plt.plotfile(fname, ('date', 'volume', 'adj_close'))
2973

74+
# Use instead:
3075
msft.plot("Date", ["Volume", "Adj. Close*"], subplots=True)
3176

32-
# Use semilogy for volume.
77+
###############################################################################
78+
# Use semilogy for volume
79+
# -----------------------
80+
81+
# Deprecated:
3382
plt.plotfile(fname, ('date', 'volume', 'adj_close'),
3483
plotfuncs={'volume': 'semilogy'})
3584

85+
# Use instead:
3686
fig, axs = plt.subplots(2, sharex=True)
3787
msft.plot("Date", "Volume", ax=axs[0], logy=True)
3888
msft.plot("Date", "Adj. Close*", ax=axs[1])
3989

40-
# Use semilogy for volume (by index).
90+
91+
###############################################################################
92+
# Use semilogy for volume (by index)
93+
# ----------------------------------
94+
95+
# Deprecated:
4196
plt.plotfile(fname, (0, 5, 6), plotfuncs={5: 'semilogy'})
4297

98+
# Use instead:
4399
fig, axs = plt.subplots(2, sharex=True)
44100
msft.plot(0, 5, ax=axs[0], logy=True)
45101
msft.plot(0, 6, ax=axs[1])
46102

103+
###############################################################################
47104
# Single subplot
105+
# --------------
106+
107+
# Deprecated:
48108
plt.plotfile(fname, ('date', 'open', 'high', 'low', 'close'), subplots=False)
49109

110+
# Use instead:
50111
msft.plot("Date", ["Open", "High", "Low", "Close"])
51112

113+
###############################################################################
52114
# Use bar for volume
115+
# ------------------
116+
117+
# Deprecated:
53118
plt.plotfile(fname, (0, 5, 6), plotfuncs={5: "bar"})
54119

120+
# Use instead:
55121
fig, axs = plt.subplots(2, sharex=True)
56122
axs[0].bar(msft.iloc[:, 0], msft.iloc[:, 5])
57123
axs[1].plot(msft.iloc[:, 0], msft.iloc[:, 6])
58124
fig.autofmt_xdate()
59125

60126
###############################################################################
127+
# Using numpy
128+
# ===========
61129

62-
# Unlabeled data.
63130
fname2 = cbook.get_sample_data('data_x_x2_x3.csv', asfileobj=False)
64131
with cbook.get_sample_data('data_x_x2_x3.csv') as file:
65132
array = np.loadtxt(file)
66133

67-
# Labeling, if no names in csv-file.
134+
###############################################################################
135+
# Labeling, if no names in csv-file
136+
# ---------------------------------
137+
138+
# Deprecated:
68139
plt.plotfile(fname2, cols=(0, 1, 2), delimiter=' ',
69140
names=['$x$', '$f(x)=x^2$', '$f(x)=x^3$'])
70141

142+
# Use instead:
71143
fig, axs = plt.subplots(2, sharex=True)
72144
axs[0].plot(array[:, 0], array[:, 1])
73145
axs[0].set(ylabel='$f(x)=x^2$')
74146
axs[1].plot(array[:, 0], array[:, 2])
75147
axs[1].set(xlabel='$x$', ylabel='$f(x)=x^3$')
76148

77-
# More than one file per figure--illustrated here with a single file.
149+
###############################################################################
150+
# More than one file per figure
151+
# -----------------------------
152+
153+
# For simplicity of the example we reuse the same file.
154+
# In general they will be different.
155+
fname3 = fname2
156+
157+
# Depreacted:
78158
plt.plotfile(fname2, cols=(0, 1), delimiter=' ')
79-
plt.plotfile(fname2, cols=(0, 2), newfig=False,
80-
delimiter=' ') # use current figure
159+
plt.plotfile(fname3, cols=(0, 2), delimiter=' ',
160+
newfig=False) # use current figure
81161
plt.xlabel(r'$x$')
82162
plt.ylabel(r'$f(x) = x^2, x^3$')
83163

164+
# Use instead:
84165
fig, ax = plt.subplots()
85166
ax.plot(array[:, 0], array[:, 1])
86167
ax.plot(array[:, 0], array[:, 2])

0 commit comments

Comments
 (0)