[R] Bode plots in ggplot2

Tribo Laboy tribolaboy at gmail.com
Fri Feb 8 17:12:36 CET 2008


Hi Hadley and Thiery

Thanks for the responses.

I worked through the code provided by Thiery and at the end I realized
that the scales for the phase and the gain are the same, which in
practice is not the case. Then I read Hadley's comment and worked with
it a bit too.  It is already quite late here, so I'll check more
details about how to lay the plots with grid tomorrow.

Here is what I have with your help so far.

# ---------------------------
# Bode plot with ggplot2
# ---------------------------

f <- c(rep(1:10,2))
gain <- rnorm(20, mean = 30 )
phase <- rnorm(20, mean = 10)
coh <- runif(20)
sys <- c(rep("system1",10), rep("system2",10))
sys_df <- data.frame( Frequency = f, Gain = gain, Phase = phase,
Coherence = coh, System = sys)


#To make a bode plot first "melt" the data frame  - requires package "reshape"
library(reshape)
library(ggplot2)
melted_sys_df <- melt(sys_df, id.var = c("Frequency", "System") )
ggtheme(theme_bw)

# This makes a bode + coherence plot on  3 facets with equal y-axes
and a color legend for "system"
#
#      Melted <- melt(bode, id.var = c("frequency", "system")
#      ggplot(Melted, aes(x = frequency, y = value, colour = system)) +
#      geom_line() + facet_grid(system ~ .) + scale_x_log10()

ggplot(melted_sys_df, aes(x = Frequency, y = value, colour = System)) +
        geom_line() + facet_grid(variable ~ .) + scale_x_log10()

# This will make separete plots with different scales, which can be
later asembled together
#
#    bode <-  ggplot(bode, aes(x = frequency, colour = system)) +
#    geom_line() + facet_grid(system ~ .) + scale_x_log10()
#
#    bode + aes(y = phase)
#    bode + aes(y = gain)

bode <-  ggplot(sys_df, aes(x = Frequency, colour = System)) +
                  geom_line() + scale_x_log10()
bode_gain <- bode + aes(y = Gain)
bode_phase <- bode + aes(y = Phase)


Thanks for the help. I'll try to make it work with grid.

Regards,

TL



More information about the R-help mailing list