From: Maximilian Friedersdorff Date: Tue, 29 Jan 2019 21:16:46 +0000 (+0000) Subject: feat: Stacked bars, pull out time series, saving X-Git-Url: https://git.friedersdorff.com/?p=max%2Fplotting_with_matplotlib.git;a=commitdiff_plain;h=55daf9eb8772ed32c57ea74be4c95e998551d2f4 feat: Stacked bars, pull out time series, saving --- diff --git a/slides.rst b/slides.rst index e49b2bd..97eca22 100644 --- a/slides.rst +++ b/slides.rst @@ -104,24 +104,35 @@ Plot data of the form: .. math:: y=f(t) .. code-block:: python - - >>> import matplotlib.pyplot as plt - >>> - >>> t = range(50) - >>> x = (ran.rand(50)*50) + 2000 # I don't have real data - >>> plt.plot(t, x) - >>> plt.title('Some time series with left title', loc='left') - >>> plt.ylabel('Mass of test mass over time') - >>> plt.show() + :include: time_series.py Subplots -------- .. code-block:: python :include: subplot.py - :end-at: ax.set_xlabel('XLabel0') + +Saving Plots +------------ + +So far I've just displayed plots with ``plt.sow()``. You can actually save +the plots from that interface manually, but when scripting, it's convenient +to do so automatically: .. code-block:: python - :include: subplot.py - :start-at: for i in range(3): + + >>> # Some plotting has previously occured + >>> plt.savefig('eggs.pdf', dpi=300, transparent=False) + +The output format is interpreted from the file extension. +The keyword arguments are optional here. Other options exist. + +Error Bars +---------- + +Stacked Bar Graph +----------------- + +.. code-block:: python + :include: stacked_bars.py diff --git a/stacked_bars.py b/stacked_bars.py new file mode 100644 index 0000000..afb9f62 --- /dev/null +++ b/stacked_bars.py @@ -0,0 +1,30 @@ +import numpy as np +import matplotlib.pyplot as plt + +N = 5 +ind = np.arange(N) # the x locations for the groups +width = 0.35 # the width of the bars + +# Shenanigans because I'm using generated data +cumulative = np.zeros(N) +legends = () + +for i in range(0,10): + sigma = np.random.rand()*10 + 10 + mu = np.random.rand()*10 + 50 + means = np.abs(sigma*np.random.randn(N) + mu) + Stds = np.abs(np.random.rand(N)*2 + 2) + + p = plt.bar(ind, means, width, yerr=Stds, + bottom=cumulative) + cumulative = cumulative + means + legends = legends + (p[0],) + +plt.ylabel('Scores') +plt.title('Scores by group and treatment') +plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5')) +plt.yticks(np.arange(0, max(cumulative), 30)) + +plt.legend(legends, range(1, len(legends) + 1)) + +plt.show() diff --git a/time_series.py b/time_series.py new file mode 100644 index 0000000..d763e22 --- /dev/null +++ b/time_series.py @@ -0,0 +1,9 @@ +import matplotlib.pyplot as plt +from numpy import random as ran + +t = range(50) +x = (ran.rand(50)*50) + 2000 # I don't have real data +plt.plot(t, x) +plt.title('Some time series with left title', loc='left') +plt.ylabel('Mass of test mass over time') +plt.show()