title: Simple data analysis with Pandas - how to remove repetitive code
body: <p>Here's an example:</p>
  
  <pre><code>import pandas as pd
  import matplotlib.pyplot as plt
  import seaborn as sns
  import matplotlib.dates as mdates
  import matplotlib.ticker as ticker
  import numpy as np
  
  dfboth = {
          'I': [1,2,3,4,5,6],
          'S': ['X', 'Y', 'X', 'Y', 'X', 'Y'], 
          'DVAR': [800, 300, 820, 330, 910, 350], 
          'CVAR': [1001, 612, 990, 639, 600, 130]}
  
  dfboth = pd.DataFrame(dfboth)
  dfboth = dfboth.assign(DVARCHANGE=dfboth['DVAR'].diff(2))
  dfboth = dfboth.assign(CVARCHANGE=dfboth['CVAR'].diff(2))
  
  plt.rcParams["figure.figsize"] = (24, 9) # (w, h)
  
  plt.subplot(2,2,1)
  plt.plot('I','DVAR', data=dfboth[dfboth.S=="X"])
  plt.plot('I','DVARCHANGE', data=dfboth[dfboth.S=="X"])
  plt.title("X-D")
  plt.legend()
  
  plt.subplot(2,2,2)
  plt.plot('I','DVAR', data=dfboth[dfboth.S=="Y"])
  plt.plot('I','DVARCHANGE', data=dfboth[dfboth.S=="Y"])
  plt.title("Y-D")
  plt.legend()
  
  plt.subplot(2,2,3)
  plt.plot('I','CVAR', data=dfboth[dfboth.S=="X"])
  plt.plot('I','CVARCHANGE', data=dfboth[dfboth.S=="X"])
  
  plt.title("X-C")
  plt.legend()
  
  plt.subplot(2,2,4)
  plt.plot('I','CVAR', data=dfboth[dfboth.S=="Y"])
  plt.plot('I','CVARCHANGE', data=dfboth[dfboth.S=="Y"])
  plt.title("Y-C")
  
  plt.legend()
  </code></pre>
  
  <p>I have a series of data points (a time series), I=1,2,3 ... and they each pertain to a certain 'S', in this example, X and Y. For each reading, we have two variables DVAR and CVAR. I am trying to make this graph <a href="https://i.stack.imgur.com/YZhc6.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/YZhc6.png" alt="like this one"></a></p>
  
  <p>I compare for S X and Y, DVAR and it's change from the previous reading, and CVAR and it's change in previous reading. </p>
  
  <p>You can also see annoying repetition. But I actually have 12 S's not just X and Y. And I have more variables.</p>
  
  <p>I believe there's a much better way of doing this than I have written using either stacked indexes or some kind of pivot table. But I've not been able to figure it out!</p>