1

Consider an X and Y relationship where, for a change in the unit system in X and Y, the numerical relationship does not change.

How can I plot this relationship in both unit systems on the same plot? (i.e. show two X axis and two Y axis for the same single plot, as opposed to showing this relationship in two separate plots)

In my particular case, I have the following two plots. The one on the right simply renders the same data normalized to represent percentages of the total quantities involved.

Here is an example :

import numpy as np
import matplotlib.pyplot as plt

ar = np.array([80, 64, 82, 72,  9, 35, 94, 58, 19, 41, 42, 18, 29, 46, 60, 14, 38,
       19, 20, 34, 59, 64, 46, 39, 24, 36, 86, 64, 39, 15, 76, 93, 54, 14,
       52, 25, 14,  4, 51, 55, 16, 32, 14, 46, 41, 40,  1,  2, 84, 61, 13,
       26, 60, 76, 22, 77, 50,  7, 83,  4, 42, 71, 23, 56, 41, 35, 37, 86,
        3, 95, 76, 37, 40, 53, 36, 24, 97, 89, 58, 63, 69, 24, 23, 95,  7,
       55, 33, 42, 54, 92, 87, 37, 99, 71, 53, 71, 79, 15, 52, 37])

ar[::-1].sort()
y = np.cumsum(ar).astype("float32")

# Normalize to a percentage
y /=y.max()
y *=100.

# Prepend a 0 to y as zero stores have zero items
y = np.hstack((0,y))

# Get cumulative percentage of stores
x = np.linspace(0,100,y.size)

# Plot the normalized chart (the one on the right)
f, ax = plt.subplots(figsize=(3,3))
ax.plot(x,y)

# Plot the unnormalized chart (the one on the left)    
f, ax = plt.subplots(figsize=(3,3))
ax.plot(x*len(ar), y*np.sum(ar))

enter image description here enter image description here

References:

  • This thread discusses how to plot multiple axes on the same plot.
  • This thread shows how to get the Lorenz plot, which is what these plots represent, given the input array ar.
Community
  • 1
  • 1
Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564

2 Answers2

1

The Original Answer

This example, from the excellent matploblib documentation, exactly solves your problem, except that you may want to use an ad hoc solution for the secondary axes' ticks (I mean, the ones with percentages).

No news from the OP

I thought "Is it possible that my answer was completely afar from the OP needs?" and shortly I felt compelled to check for myself... Following the link and working a little bit I was able to obtain the plot below (please note, my data differ from OP's data)

enter image description here

that seems similar to the OP request, but who knows? Is my original answer not good enough? What else have I to do for my answer being accepted?

gboffi
  • 22,939
  • 8
  • 54
  • 85
0

Try this

# Plot the normalized chart (the one on the right)
f, ax = plt.subplots(figsize=(3,3))
ax.plot(x,y)
ax1 = ax.twinx().twiny()
ax1.plot(x*len(ar), y*np.sum(ar), 'r')

enter image description here

Kirubaharan J
  • 2,255
  • 16
  • 23