Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
552 views
in Technique[技术] by (71.8m points)

r - ggplot not outputting values in dataframe

I have the following dataframe:

Year Ocean      O2_Conc
   <dbl> <chr>        <dbl>
 1 2010. Reference 0.000237
 2 2010. Pacific   0.000165
 3 2010. Southern  0.000165
 4 2012. Reference 0.000237
 5 2012. Pacific   0.000165
 6 2012. Southern  0.000165
 7 2012. Reference 0.000237
 8 2012. Pacific   0.000165
 9 2012. Southern  0.000165

I would like to plot this data in ggplot2 to produce a scatter plot with different oceans as different colours. I have tried the following code, which has worked for similar data:

ggplot(data=df, aes(x="Year", y="O2_Conc", color="Ocean")) + geom_point()

This has given me this output. Can someone explain why the numbers are not coming through on the graph's axes? GGplot output


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The following code plots the points, not the string "Ocean" but does more. It creates a new variable n counting the repeats of O2_Conc by year and ocean and treats the years as dates.

library(ggplot2)
library(dplyr)

df %>% 
  group_by(Year, Ocean) %>%
  mutate(n = n()) %>%
  mutate(Year = as.Date(paste(Year, "01", "01", sep = "-"))) %>%
  ggplot(aes(Year, O2_Conc, color = Ocean)) +
  geom_point(aes(size = n), alpha = 0.5, show.legend = FALSE) +
  scale_x_date(date_breaks = "year", date_labels = "%Y")

Data

df <- read.table(text = "
Year Ocean      O2_Conc
 1 2010. Reference 0.000237
 2 2010. Pacific   0.000165
 3 2010. Southern  0.000165
 4 2012. Reference 0.000237
 5 2012. Pacific   0.000165
 6 2012. Southern  0.000165
 7 2012. Reference 0.000237
 8 2012. Pacific   0.000165
 9 2012. Southern  0.000165
", header = TRUE)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...