简体   繁体   中英

Python Graph that shows relationship between three variables

I have a Python Function that has the arguments Slope and Distance and it returns Cost . Slope can be in the range 1 - 80. Distance can be in the range 1 - 20000. Cost can be any positive number.

I want to see the relationship between slope, distance, and cost. What would be the best plot to show the relationship between these three variables? And how would I create it. I want to know for instance what happens to cost if slope goes up and distance down? What happens to cost if slope and distance go up? etc...

def func(Slope, Distance):
     ...
     return cost


SlopeList = list(xrange(81))
DistanceList = list(xrange(20000)



myList= []
for Distance in DistanceList:
    for Slope in SlopeList:   
         cost = func(Slope, Distance)
         var = (Slope, Distance, Cost)
         append.myList(var)

The question is a bit unclear, so I'll try to cover all the possibilities:

a) If you have a function of two variables, like func , and you can execute that function for many combinations of the two variables, you can use matplotlib to draw a contour plot with (perhaps) Slope and Distance on the x and y axes respectively, and Cost shown as contours. See here for an example.

b) If you have a function such as:

Cost = func(Slope,Distance)

... and you know Cost and the value of one of the other two variables, then you could either:

b1) Write two more functions (eg funcSlope(Cost,Distance) and funcDistance(Slope,Cost) ) that produce the unknown variable from the known variables, or

b2) If either the function func is unavailable to you, so you don't know how it is computed and therefore cannot explicitly write the functions that I've suggested for option 1, or it is hard to invert func analytically to find Slope or Distance from the other two variables, you can find the unknown variable numerically using code that is something like this:

def func(Slope,Distance):
    # Imagine that we didn't know the definition of this function
    # so we couldn't write funcSlope() explicitly
    return Slope * Distance**0.1234

def funcSlope(Cost,Distance,minSlope,maxSlope):
    def fs (Slope):
        return Cost - func(Slope,Distance)
    return scipy.optimize.brentq(fs, minSlope, maxSlope)

print (func(2,6))
print (funcSlope(2.4949,6,0,10))

... for which the output is:

2.494904118641096
1.999996698357211

You'll see that you need to specify bounds for the unknown variable when calling brentq() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM