0

This looks like it's fairly close to the answer I'm looking for but it's not quite there. Perhaps I'm not following the "tidy data" principles and will need to make a dataframe evaluated at many points to plot these functions but I'm hesitant to accept that as the answer.

Here's the code to plot the graph I have.

call_value_per_unit = lambda s_t1,X: max(0, s_t1-X)
put_value_per_unit = lambda s_t1, X: max(0, X-s_t1)
put_call_value = lambda s_t1, X: put_value_per_unit(s_t1, X) + call_value_per_unit(s_t1, X)

independent_variable = "Stock Price"
dependent_variable = "Asset Price"

g = ggplot(pd.DataFrame({independent_variable:[10,20]}), aes(x=independent_variable)) \
         + stat_function(fun=put_value_per_unit, args=[15], color="red") \
         + stat_function(fun=call_value_per_unit, args=[15], color="blue") \
         + stat_function(fun=put_call_value, args=[15], color="black") \
         + ylab(dependent_variable) \
         + ggtitle(" ".join([independent_variable , "vs", dependent_variable]))
_ = g.draw()

But there's no legend... And I'd like there to be one.

(Although I'm in python, R users will likely have good suggestions)

financial_physician
  • 1,672
  • 1
  • 14
  • 34

2 Answers2

1

In R, to plot functions with package ggplot2, first define a data set with a x vector. Then use stat_function with an appropriate geom. This usually is one of

  • geom = "line"
  • geom = "point"

Then, it's very simple to graph the function.

library(ggplot2)

df1 <- data.frame(x = -5:5)

ggplot(df1, aes(x)) +
  stat_function(geom = "line", fun = function(x) x^2)

enter image description here

Rui Barradas
  • 70,273
  • 8
  • 34
  • 66
1

Plotting multiple functions in one plot and having a legend for each function is not possible. For stat_function, func is a parameter not an aesthetic so you cannot map a variable/column to it. Legends only help interpret aesthetic mappings.

Since you want to do heavy many computations, do that outside the plotting calls then plot the results with geom_line. Make sure your dataframe is in tidy data form. Do not let the fact that there is a stat_function force you into using when it is not the best tool for the job.

has2k1
  • 2,095
  • 18
  • 16
  • 1
    I think this is the best answer, it walks through what's wrong with what I want to do, why I should do it differently, and then how to go about it differently. Thank you! – financial_physician Apr 20 '20 at 21:36