r - Sharing a Legend between two combined ggplots -
I am currently trying to present the series twice using two ggplot2, both with very different scales, Using two ggplots. By using Because it can be relevant, I am currently working in the range of creating a shining section of an R mark document. Therefore The following is the code I have. Is there a suggestion about creating a shared lion? Thanks for your help. Method 1: When the scales are the same using Method 2: When the scales are wildly vulnerable As you can see, the last plot is great! You need to create a conspiracy to keep your legend; Pass it as a custom function created in custom parameters. grid.arrange , I've added two separate ggplots on top of each other. For visualization support, I want to make each row a different color, and this story is given below under the joint conspiracy.
grid.arrange . Renderplate wrapper around;
testdata = data.frame (Var1 = seq (0, 10, = 1), var2 = runif (11), var3 = runif (11, min = 100, max = 500)) Render plot ({grid.arrange (ggplot (data = test data, ace (x = var1, y = var2)) + geom_line (color = "blue") + xlab (null), ggplot (data = testdata, aes (x = Var1, y = var3)) + geom_line (color = "red")}}
ggplot2 < / P>
facet_grid By using or just the
color parameter in combination with the
reshape2 package, you can easily add multiple plots with the same legend. The values of your variable have the same order of magnitude, so this is ideal.
color &
reshape2 :
Library ('reshape2') data_melt & lt; -melt (data = testdata, value.name = 'value', id.vars = 'var1') ggplot (data_melt) + geom_line (aes (x = var1, y = value, color = variable)) < / Pre>
testdata = data.frame (var1 = seq (0, 10, by = 1), var2 = runif (11), var3 = runif (11, min = 100, max = 500) ) Library ('reshape2') data_melt & lt; -melt (data = test data, value.name = 'value', id.vars = 'var1') p1 = ggplot (data = testdata) + geom_line (aes (x = var1, y = var2, color = 'blue') ) P2 = ggplot (data = testdata) + geom_line (aes (x = var1, y = var3, color = 'red')) p3 = ggplot (data_melt) + geom_line (aes (x = var1, y = value, color = Variable)) grid.arrange (P1, P2, Nrow = 2, main = 'line plot') g_legend & lt; Function (a.gplot) {tmp & lt; - ggplot_gtable (ggplot_build (a.gplot)) leg & lt; - who (sapply (tmp $ grobs, function (x) $ name) == "guide-box") Legend & lt; - TMP $ grobs [[Legs]] Return (legend)} Legend & lt; - g_legend (p3) lwidth & lt; - Zodiac (Legend $ width) # # # Use of grid for feature # can also manually organize the viewports grid. ArrangeGrob (p1 + theme (legend.position = "none"), P2 + theme (legend.position = "none"), main = "variable name", left = "val Ue"), legend, width = unit Unit (1, "NPC") - Elvideth, LWDith), NRO = 1)
Comments
Post a Comment