I am trying to create a contour plot. I have loaded a list of csv's into a combined_df. There are three columns - tau, time and gamma. Tau is the x axis, time is the y axis and gamma is what I want to give the intensity in the contour plot. Each 'time' is a particular csv. My current script is:
# Function to read and process a single CSV file
process_csv <- function(file_name, time_stamp) {
# Read the CSV file, skipping the first three rows
df <- read_csv(file_name, skip = 3)
# Use the CSV name as a time stamp
df$time <- time_stamp
# Convert tau to log10 scale
df$tau <- log10(df$tau)
return(df)
}
# List of CSV files (assuming they are in your working directory)
filelist_grad = list.files(pattern = "*.csv")
csv_files <- stringr::str_sort(filelist_grad, numeric = TRUE)
csv_files
# Time stamps based on CSV file names
time_stamps <- seq(0.5, by = 0.5, length.out = length(csv_files))
# Process each CSV file and combine them into a single data frame
data_list <- mapply(process_csv, csv_files, time_stamps, SIMPLIFY = FALSE)
combined_df <- bind_rows(data_list)
# Interpolate data to a regular grid
d1 <- with(combined_df, interp(x = tau, y = time, z = gamma))
# Melt the z matrix to long format
d2 <- melt(d1$z, na.rm = TRUE)
names(d2) <- c("x", "y", "gamma")
# Add NMDS1 and NMDS2 from d1
d2$NMDS1 <- d1$x[d2$x]
d2$NMDS2 <- d1$y[d2$y]
# Create the plot
ggplot(data = d2, aes(x = NMDS1, y = NMDS2, z = gamma, group = cut_number(gamma, g=100))) +
geom_contour_filled(bins = 20, breaks = seq(0, 120, by = 10)) +
scale_fill_gradient(limits = c(0, 100), low = "yellow", high = "red") +
theme_minimal()
This gives me this error:
Error in geom_contour_filled()
:
! Problem while computing aesthetics.
i Error occurred in the 1st layer.
Caused by error in breaks()
:
! Specify exactly one of n
and width
.
I'm not really sure how to fix - any help is much appreciated!!I'm happy to forward on example data - my data is quite large and is quite hard to produce a reproducible example of which fits in the box!
Do you get the same error if you use n = 100
in your cut_number()
, instead of g = 100
, and use more breaks?
E.g. using the built-in ggplot2 dataset faithfuld
:
library(tidyverse)
faithfuld %>%
ggplot(aes(x = log10(waiting), y = eruptions, z = 100 * density,
group = cut_number(density, n = 100))) +
geom_contour_filled(bins = 20, breaks = seq(0, 120, by = 1))
Created on 2024-06-20 with reprex v2.1.0