|
| 1 | +""" |
| 2 | +========================= |
| 3 | +Plotting data from a file |
| 4 | +========================= |
| 5 | +
|
| 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. |
| 21 | +""" |
| 22 | + |
| 23 | +import matplotlib.pyplot as plt |
| 24 | +import matplotlib.cbook as cbook |
| 25 | + |
| 26 | +import numpy as np |
| 27 | +import pandas as pd |
| 28 | + |
| 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 | + |
| 42 | +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 | + |
| 53 | +with cbook.get_sample_data('msft.csv') as file: |
| 54 | + msft = pd.read_csv(file, parse_dates=['Date']) |
| 55 | + |
| 56 | + |
| 57 | +############################################################################### |
| 58 | +# Use indices |
| 59 | +# ----------- |
| 60 | + |
| 61 | +# Deprecated: |
| 62 | +plt.plotfile(fname, (0, 5, 6)) |
| 63 | + |
| 64 | +# Use instead: |
| 65 | +msft.plot(0, [5, 6], subplots=True) |
| 66 | + |
| 67 | +############################################################################### |
| 68 | +# Use names |
| 69 | +# --------- |
| 70 | + |
| 71 | +# Deprecated: |
| 72 | +plt.plotfile(fname, ('date', 'volume', 'adj_close')) |
| 73 | + |
| 74 | +# Use instead: |
| 75 | +msft.plot("Date", ["Volume", "Adj. Close*"], subplots=True) |
| 76 | + |
| 77 | +############################################################################### |
| 78 | +# Use semilogy for volume |
| 79 | +# ----------------------- |
| 80 | + |
| 81 | +# Deprecated: |
| 82 | +plt.plotfile(fname, ('date', 'volume', 'adj_close'), |
| 83 | + plotfuncs={'volume': 'semilogy'}) |
| 84 | + |
| 85 | +# Use instead: |
| 86 | +fig, axs = plt.subplots(2, sharex=True) |
| 87 | +msft.plot("Date", "Volume", ax=axs[0], logy=True) |
| 88 | +msft.plot("Date", "Adj. Close*", ax=axs[1]) |
| 89 | + |
| 90 | + |
| 91 | +############################################################################### |
| 92 | +# Use semilogy for volume (by index) |
| 93 | +# ---------------------------------- |
| 94 | + |
| 95 | +# Deprecated: |
| 96 | +plt.plotfile(fname, (0, 5, 6), plotfuncs={5: 'semilogy'}) |
| 97 | + |
| 98 | +# Use instead: |
| 99 | +fig, axs = plt.subplots(2, sharex=True) |
| 100 | +msft.plot(0, 5, ax=axs[0], logy=True) |
| 101 | +msft.plot(0, 6, ax=axs[1]) |
| 102 | + |
| 103 | +############################################################################### |
| 104 | +# Single subplot |
| 105 | +# -------------- |
| 106 | + |
| 107 | +# Deprecated: |
| 108 | +plt.plotfile(fname, ('date', 'open', 'high', 'low', 'close'), subplots=False) |
| 109 | + |
| 110 | +# Use instead: |
| 111 | +msft.plot("Date", ["Open", "High", "Low", "Close"]) |
| 112 | + |
| 113 | +############################################################################### |
| 114 | +# Use bar for volume |
| 115 | +# ------------------ |
| 116 | + |
| 117 | +# Deprecated: |
| 118 | +plt.plotfile(fname, (0, 5, 6), plotfuncs={5: "bar"}) |
| 119 | + |
| 120 | +# Use instead: |
| 121 | +fig, axs = plt.subplots(2, sharex=True) |
| 122 | +axs[0].bar(msft.iloc[:, 0], msft.iloc[:, 5]) |
| 123 | +axs[1].plot(msft.iloc[:, 0], msft.iloc[:, 6]) |
| 124 | +fig.autofmt_xdate() |
| 125 | + |
| 126 | +############################################################################### |
| 127 | +# Using numpy |
| 128 | +# =========== |
| 129 | + |
| 130 | +fname2 = cbook.get_sample_data('data_x_x2_x3.csv', asfileobj=False) |
| 131 | +with cbook.get_sample_data('data_x_x2_x3.csv') as file: |
| 132 | + array = np.loadtxt(file) |
| 133 | + |
| 134 | +############################################################################### |
| 135 | +# Labeling, if no names in csv-file |
| 136 | +# --------------------------------- |
| 137 | + |
| 138 | +# Deprecated: |
| 139 | +plt.plotfile(fname2, cols=(0, 1, 2), delimiter=' ', |
| 140 | + names=['$x$', '$f(x)=x^2$', '$f(x)=x^3$']) |
| 141 | + |
| 142 | +# Use instead: |
| 143 | +fig, axs = plt.subplots(2, sharex=True) |
| 144 | +axs[0].plot(array[:, 0], array[:, 1]) |
| 145 | +axs[0].set(ylabel='$f(x)=x^2$') |
| 146 | +axs[1].plot(array[:, 0], array[:, 2]) |
| 147 | +axs[1].set(xlabel='$x$', ylabel='$f(x)=x^3$') |
| 148 | + |
| 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: |
| 158 | +plt.plotfile(fname2, cols=(0, 1), delimiter=' ') |
| 159 | +plt.plotfile(fname3, cols=(0, 2), delimiter=' ', |
| 160 | + newfig=False) # use current figure |
| 161 | +plt.xlabel(r'$x$') |
| 162 | +plt.ylabel(r'$f(x) = x^2, x^3$') |
| 163 | + |
| 164 | +# Use instead: |
| 165 | +fig, ax = plt.subplots() |
| 166 | +ax.plot(array[:, 0], array[:, 1]) |
| 167 | +ax.plot(array[:, 0], array[:, 2]) |
| 168 | +ax.set(xlabel='$x$', ylabel='$f(x)=x^3$') |
| 169 | + |
| 170 | +plt.show() |
0 commit comments