Learn R Programming

openaiRtools (version 0.2.2)

image_from_plot: Create Image Content from an R Plot Object

Description

Renders a ggplot2 plot (or any R base graphics expression) to a temporary PNG file and encodes it as Base64, ready to be sent to a vision LLM. This lets you analyze charts produced in R without saving them manually.

Usage

image_from_plot(plot = NULL, width = 7, height = 5, dpi = 150, detail = "auto")

Value

A named list (content part) ready to include in a message's content list.

Arguments

plot

A ggplot object (ggplot2), or NULL to capture the current base-R graphics device (call your plot()/ hist() etc. first, then call image_from_plot(NULL)).

width

Numeric. Width of the saved PNG in inches. Default: 7.

height

Numeric. Height of the saved PNG in inches. Default: 5.

dpi

Integer. Resolution in dots per inch. Higher DPI gives sharper images (important for text readability) but larger file size. Default: 150. Use 200+ when text in plots must be legible.

detail

Character. Image detail level passed to the API: "auto" (default), "low", or "high".

See Also

image_from_file, create_multimodal_message

Examples

Run this code
if (FALSE) {
library(openaiRtools)
library(ggplot2)
client <- OpenAI$new(api_key = "sk-xxxxxx")

# Build a ggplot2 chart
p <- ggplot(mtcars, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(method = "lm") +
  labs(title = "Car Weight vs Fuel Efficiency", x = "Weight", y = "MPG")

# Send plot directly to GPT-4o
response <- client$chat$completions$create(
  messages = list(
    list(
      role = "user",
      content = list(
        list(
          type = "text",
          text = "Describe the relationship shown in this scatter plot."
        ),
        image_from_plot(p, dpi = 150)
      )
    )
  ),
  model = "gpt-4o"
)
cat(response$choices[[1]]$message$content)
}

Run the code above in your browser using DataLab