Reputation: 43
I'm trying to create a lollipop chart with ggplot2 where my data is ordered by Class
.
Here's my code so far:
FinalAA_class <- read_csv(file = "/cloud/project/Data/FinalAAs_classes.csv")
FinalB <- slice(FinalAA_class, 1:17)
bFinalAA2 <- ggplot(FinalB, aes(x=EndAA, y=CountAA, fill=Class, colour=Class)) +
geom_point() + geom_segment( aes(x=EndAA, xend=EndAA, y=0, yend=CountAA)) +
xlab("Amino acid") + ylab("Count")
My data:
structure(list(Name = c("bitter", "bitter", "bitter", "bitter",
"bitter", "bitter", "bitter", "bitter", "bitter", "bitter", "bitter",
"bitter", "bitter", "bitter", "bitter", "bitter", "bitter"),
Class = c("Aliphatic", "Aliphatic", "Aliphatic", "Aliphatic",
"Aliphatic", "Acidic", "Acidic", "Acidic", "Aromatic", "Aromatic",
"Basic", "Basic", "Basic", "Polar", "Polar", "Polar", "Polar"
), EndAA = c("A", "I", "L", "V", "G", "D", "Q", "E", "W",
"F", "H", "K", "R", "T", "N", "S", "P"), CountAA = c(7, 17,
29, 41, 55, 5, 5, 13, 6, 57, 3, 7, 16, 1, 3, 4, 28)), class =
c("spec_tbl_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -17L), spec =
structure(list(
cols = list(Name = structure(list(), class = c("collector_character",
"collector")), Class = structure(list(), class = c("collector_character",
"collector")), EndAA = structure(list(), class = c("collector_character",
"collector")), CountAA = structure(list(), class = c("collector_double",
"collector"))), default = structure(list(), class = c("collector_guess",
"collector")), skip = 1), class = "col_spec"))
I want to order the graph so the lines appear in ascending order starting with Acidic and ending with Polar. (Same as the order it is in in the table).
Please see the hyperlink for the graph.
Upvotes: 0
Views: 1225
Reputation: 174448
You need to reorder the levels of FinalB$EndAA
according to the order of the levels in FinalB$Class
. You can do this with fct_reorder
from forcats
:
library(ggplot2)
library(forcats)
FinalB$EndAA <- fct_reorder(FinalB$EndAA, FinalB$CountAA)
FinalB$EndAA <- fct_reorder(FinalB$EndAA, FinalB$Class)
ggplot(FinalB, aes(x=EndAA, y=CountAA, fill=Class, colour=Class)) +
geom_point() + geom_segment( aes(x=EndAA, xend=EndAA, y=0, yend=CountAA)) +
xlab("Amino acid") + ylab("Count")
Created on 2020-06-29 by the reprex package (v0.3.0)
Upvotes: 1