简体   繁体   中英

Plotting multiple lines in R

I'm pretty new to R so I don't really know what I'm doing. Anyway, I have data in this format in excel (as a csv file):

dt <- data.frame(species = rep(c("a", "b", "c"), each = 4),
                 cover = rep(1:3, times = 4),
                 depth = rep(c(15, 30, 60, 90), times = 3),
                 stringsAsFactors = FALSE)

I want to plot a graph of cover against depth, with a different coloured line for each species, and a key for which species is which colour. I don't even know where to start.

Sorry if something similar has been asked before. Any help would be much appreciated!

Don't know if this is in a helpful format but here's some of the actual data, I need to read more about dput I think:

structure(list(species = structure(c(1L, 1L, 2L, 2L, 3L, 3L, 
4L, 4L, 5L, 5L, 6L, 6L, 7L, 7L, 8L, 8L, 9L, 9L, 10L, 10L, 11L, 
11L), .Label = c("Agaricia fragilis", "bryozoan", "Dichocoenia stokesi", 
"Diploria labyrinthiformis", "Diploria strigosa", "Madracis decactis", 
"Manicina", "Montastrea cavernosa", "Orbicella franksi", "Porites asteroides", 
"Siderastrea radians"), class = "factor"), cover = c(0.021212121, 
0.04047619, 0, 0, 0, 0, 1.266666667, 4.269047619, 3.587878788, 
3.25, 0.118181818, 0.152380952, 0, 0.007142857, 3.806060606, 
2.983333333, 14.13030303, 15.76190476, 0.415151515, 0.2, 0.26969697, 
0.135714286), depth = c(30L, 15L, 30L, 15L, 30L, 15L, 30L, 15L, 
30L, 15L, 30L, 15L, 30L, 15L, 30L, 15L, 30L, 15L, 30L, 15L, 30L, 
15L)), .Names = c("species", "cover", "depth"), row.names = c(NA, 
22L), class = "data.frame")

Here is a solution using the ggplot2 package.

# Load packages
library(ggplot2)

# Create example data frame based on the original example the OP provided
dt <- data.frame(species = rep(c("a", "b", "c"), each = 4),
                 cover = rep(1:3, times = 4),
                 depth = rep(c(15, 30, 60, 90), times = 3),
                 stringsAsFactors = FALSE)

# Plot the data
ggplot(dt, aes(x = depth, y = cover, group = species, colour = species)) +
  geom_line()

This should get you going!

  df1 <- read.csv("//file_location.csv", headers=T)
  library(dplyr)
  df1 <- df1 %>% select(species, depth) %>% group_by(species) %>%
  summarise(mean(depth)
  library(ggplot2)
  ggplot(df1, aes(x=depth, y=species, group=species, color=species) +
  geom_line()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM