pythonmatplotlibplotnatural-logarithm

Matplotlib plotting ln functions


Ok, so Im not sure if this is even possible. I am trying to plot a graph in python, using matplotlib, that has a natural log function of both x and y.

First, I looked for posts containing instructions on how-to plot using a natural log. I found part of an answer here and the other part here.

The problem is, I am trying to plot two lines onto one graph.

The equations are:

1) 0.91 - 0.42 * P = Q

2) 6.999 - .7903 * ln (P) = ln (Q)

Is it possible to overlay these two lines onto one graph given the scale issue? How would I do it?

I tried the following:

from pylab import *
import matplotlib.pyplot as plt
import matplotlib
get_ipython().magic('matplotlib inline')
import numpy as np
import pandas as pd

P = np.linspace(0, 1, 11)

P

matplotlib.rcParams['xtick.major.pad'] = 5
matplotlib.rcParams['ytick.major.pad'] = 5

fig, ax = plt.subplots(figsize = (12,6))

axes = plt.gca()
axes.set_ylim([0, 16])

ax.plot(P, 0.91 - 0.42 * P, color = "BLUE", lw = 3, label = 'C1')

x = P ** np.e
y = 6.999 - .7903 * x
y1 = y ** np.e
ax.loglog(x, y, basex = np.e, basey = np.e)
ax.legend()

ax.set_title("Cluster 1 Pricing")

ax.xaxis.labelpad = 5
ax.yaxis.labelpad = 5

ax.set_xlabel("Norm P")
ax.set_ylabel("Norm Q");

But this returns the error:

ValueError: posx and posy should be finite values


Solution

  • It seems you want to plot

    q1 = lambda p: 0.91 - 0.42 * p
    q2 = lambda p: np.exp(6.999 - .7903 * np.log(p)) 
    

    This can be done by supplying an array P to those functions and using the plot functions you already have in the code. Mind that you should not attempt to plot 0 on a logrithmic scale.

    import matplotlib.pyplot as plt
    import numpy as np
    
    P = np.linspace(0.01, 1, 11)
    
    fig, ax = plt.subplots(figsize = (12,6))
    
    q1 = lambda p: 0.91 - 0.42 * p
    q2 = lambda p: np.exp(6.999 - .7903 * np.log(p)) 
    
    ax.plot(P, q1(P), color = "BLUE", lw = 3, label = 'Q1')
    
    ax.loglog(P, q2(P), basex = np.e, basey = np.e,
              color = "crimson", lw = 2, label = 'Q2')
    ax.legend()
    
    
    ax.set_title("Cluster 1 Pricing")
    ax.set_xlabel("Norm P")
    ax.set_ylabel("Norm Q")
    
    plt.show()
    

    enter image description here