How to do it...

  1. Import matplotlib:
>>> import matplotlib.pyplot as plt
  1. Prepare the data to be displayed on the graph, and the legends that should be displayed. Each of the lines is composed of the time label, sales of ProductA, sales of ProductB, and sales of ProductC:
>>> LEGEND = ('ProductA', 'ProductB', 'ProductC')
>>> DATA = (
... ('Q1 2017', 100, 30, 3),
... ('Q2 2017', 105, 32, 15),
... ('Q3 2017', 125, 29, 40),
... ('Q4 2017', 115, 31, 80),
... )
  1. Split the data into usable formats for the graph. This is a preparation step:
>>> POS = list(range(len(DATA)))
>>> VALUESA = [valueA for label, valueA, valueB, valueC in DATA]
>>> VALUESB = [valueB for label, valueA, valueB, valueC in DATA]
>>> VALUESC = [valueC for label, valueA, valueB, valueC in DATA]
>>> LABELS = [label for label, valueA, valueB, valueC in DATA]
  1. Create a bar graph with the data:
>>> WIDTH = 0.2
>>> plt.bar([p - WIDTH for p in POS], VALUESA, width=WIDTH)
>>> plt.bar([p for p in POS], VALUESB, width=WIDTH)
>>> plt.bar([p + WIDTH for p in POS], VALUESC, width=WIDTH)
>>> plt.ylabel('Sales')
>>> plt.xticks(POS, LABELS)
  1. Add an annotation displaying the maximum growth in the chart:
>>> plt.annotate('400% growth', xy=(1.2, 18), xytext=(1.3, 40),
horizontalalignment='center',
arrowprops=dict(facecolor='black', shrink=0.05))

  1. Add the legend:
>>> plt.legend(LEGEND)
  1. Display the graph:
>>> plt.show()
  1. The result will be displayed in a new window:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.15.154.69