Matplotlib 3.0 Cookbook
上QQ阅读APP看书,第一时间看更新

Twin axes

Sometimes, we may want to plot two charts on the same axes, but have a different scale of data. If we use a standard plot with the same scale on the left and right spines, charts may not look right due to a large difference in their scale of data. In such cases, we can use the twin axes feature provided by Matplotlib. We will learn how to use it in this recipe.

We will use product defects data for a month in a manufacturing plant for this example. We will draw a bar plot of the number of defects by reason code (for example 0 to 5, representing various reasons for producing defective products) and cumulative percentage line graph (sum total of defective products aggregated over reason codes).

There are three options for twinning the axes:

  • twinx: Shares the x axis for both the graphs, while the left and right axes denote two different scales
  • twiny: Shares the y axis for both the graphs, while the top and bottom axis denote two scales
  • no sharing: Where the bottom and the left axis are used by one graph, and the top and right axis are used by the second graph

We will learn how to implement all three possibilities in this recipe.