Enhanced Contour Plots with filled.contour()
The filled.contour() function enhances the basic contour plot by filling the spaces between contour lines with colors, making it easier to interpret the data.
Filled Contour Plot
Here’s an example of how to create a filled contour plot using the filled.contour()
function:
filled.contour(x, y, z, color.palette = terrain.colors,
plot.title = title(main = "Filled Contour Plot", xlab = "X-axis",
ylab = "Y-axis"))
Output:
This command creates a filled contour plot with colors specified by the terrain.colors palette.
Advanced Contour Plots with ggplot2
The ggplot2 package offers more flexibility and control over the appearance of contour plots. The geom_contour() and geom_contour_filled() functions are used for this purpose.
install.packages("ggplot2")
library(ggplot2)
# Create a data frame for ggplot2
library(ggplot2)
library(dplyr)
df <- expand.grid(x = x, y = y) %>%
mutate(z = sin(sqrt(x^2 + y^2)))
# Basic contour plot
ggplot(df, aes(x = x, y = y, z = z)) +
geom_contour() +
labs(title = "Contour Plot with ggplot2", x = "X-axis", y = "Y-axis")
Output:
Filled Contour Plot with ggplot2
Creating a filled contour plot with ggplot2 involves using the geom_contour_filled()
function to represent the contours as filled polygons.
# Filled contour plot
ggplot(df, aes(x = x, y = y, z = z)) +
geom_contour_filled() +
labs(title = "Filled Contour Plot with ggplot2", x = "X-axis", y = "Y-axis")
Output:
These examples demonstrate how to create both basic and filled contour plots using ggplot2.
Interactive Contour Plots with plotly
For interactive contour plots, the plotly package is a great choice. It allows users to hover over the plot to see the values of the data points.
install.packages("plotly")
library(plotly)
# Create a data frame for plotly
df <- expand.grid(x = x, y = y)
df$z <- sin(sqrt(df$x^2 + df$y^2))
# Interactive contour plot
plot_ly(x = ~df$x, y = ~df$y, z = ~df$z, type = "contour") %>%
layout(title = "Interactive Contour Plot", xaxis = list(title = "X-axis"),
yaxis = list(title = "Y-axis"))
Output:
This code creates an interactive contour plot where users can explore the data by hovering over different areas.
Contour Plot in R
In this article, we will discuss Contour Plot and different ways to create a Contour Plot in the R Programming Language.