I have the following plot
require(ggplot2)
dtf <- structure(list(Variance = c(5.213, 1.377, 0.858, 0.613, 0.412, 0.229, 0.139, 0.094, 0.064), Component = structure(1:9, .Label = c("PC1", "PC2", "PC3", "PC4", "PC5", "PC6", "PC7", "PC8", "PC9"), class = "factor")), .Names = c("Variance", "Component"), row.names = c(NA, -9L), class = "data.frame")
ggplot(dtf, aes(x = Component, y = Variance)) +
geom_point()
I would simply like to connect the dots with straight lines. I tried +geom_line() but that generated an error
Your x values are discrete (factor) and geom_line() each unique x value perceive as separate group and tries to connect points only inside this group. Setting group=1 in aes() ensures that all values are treated as one group.
ggplot(dtf, aes(x = Component, y = Variance,group=1)) +
geom_point()+geom_line()
This would plot the points with x as the integer values of the factor categories:
ggplot(dtf, aes(x = as.numeric(Component), y = Variance)) +
geom_point() + geom_line()
You can put back in the category labels with:
ggplot(dtf, aes(x = as.numeric(Component), y = Variance)) +
geom_point() +geom_line() + scale_x_discrete(labels=dtf$Component)
Related
Given this simple data I want to plot the equivalent of base
plot(dat$value)
but with ggplot.
dat= structure(list(name = c("Cord", "Cord",
"amo", "amo",
"amo", "ramo"),
value = c(7, 0.7, 9,
0.9, 0.8, 0.7)), row.names = c(NA,
6L), class = "data.frame")
I tried:
> ggplot(data = dat) + geom_point(aes(x = value, colour = name))
Error in `check_required_aesthetics()`:
! geom_point requires the following missing aesthetics: y
I need to plot "count" on y axis vs value on x axis
You could create a row index using tibble::rownames_to_column, then use that to plot along the x-axis, so that you get a similar result to plot(dat$value).
library(tidyverse)
dat %>%
rownames_to_column("ind") %>%
ggplot(aes(x = ind, y = value, color = name)) +
geom_point(size = 3) +
theme_bw()
Output
Or you can put the function directly into ggplot:
ggplot(dat, aes(
x = rownames_to_column(dat)$rowname,
y = value,
color = name
)) +
geom_point(size = 3) +
theme_bw()
Or another option is to use row.names:
ggplot(dat, aes(x = as.numeric(row.names(dat)), y = value, colour = name)) +
geom_point()
Base R plot(dat$value) has an implicit x equal to seq_along(dat$value).
Use x = seq_along(value) and y = value.
dat <- structure(list(name = c("Cord", "Cord",
"amo", "amo",
"amo", "ramo"),
value = c(7, 0.7, 9,
0.9, 0.8, 0.7)),
row.names = c(NA, 6L),
class = "data.frame")
library(ggplot2)
ggplot(dat, aes(x = seq_along(value), y = value, color = name)) +
geom_point()
Created on 2022-03-01 by the reprex package (v2.0.1)
I have the following dataset
structure(list(X = c(9.8186734, 19.6373468, 29.4560202, 39.2746936,
49.093367, 58.9120404, 68.7307138, 78.5493872, 88.3680606, 98.186734
), Y = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1), radii = c(530.595715856625,
530.595715856625, 524.270569515141, 520.785212389348, 524.423046929159,
524.777454042683, 523.089321742221, 522.852371975715, 523.124870390148,
522.612174462367), slope = c(-21.796356958782, -21.796356958782,
-21.796356958782, -21.796356958782, -21.796356958782, -21.796356958782,
-21.796356958782, -21.796356958782, -21.796356958782, -21.796356958782
)), row.names = c(NA, -10L), class = c("data.table", "data.frame"
), .internal.selfref = <pointer: 0x7f989f011ce0>, sorted = "Y")
and I am simply trying to print slope as a text to the figure as
str_slope <- c(substitute("Slope = "~sp~mu*"m/s", list(sp = sprintf("%2.1f", dt[!duplicated(slope), slope]))))
d_text <- data.table(x=2000, y=500, label = str_slope)
ggplot(dt, aes(x = X, y=radii)) +
geom_point()+
geom_smooth(method = "lm", level = 0.9999, se = TRUE)+
scale_colour_manual(values = getPalette) +
labs(x = "time (s)", y = expression("radius ["*mu*"m]"), color = "Speed [µm/s]") +
geom_text(data = d_text, aes(x = x, y = y, label = label))+
theme_default(legend.position = "none")
but I get something like this
Why is the text in str_slope not evaluated as an expression? How can I force ggplot to interpret it as an expression, so that the text will look like
For this type of plot annotation, you should use annotate(geom="text"...) rather than geom_text(). For how to generate the expression, you can use the parse=TRUE argument within annotate().
I think we're missing all your plot data, so here's an example with mtcars that incorporates the contents of str_slope in your example.
str_slope <- c(substitute("Slope = "~sp~mu*"m/s", list(sp = sprintf("%2.1f", dt[!duplicated(slope), slope]))))
p <- ggplot(mtcars, aes(x = wt, y = mpg)) + geom_point()
p + annotate(
"text", x=4, y=25,
label= str_slope, parse=TRUE)
For your information, geom_text() is designed to be used wherein one or more aesthetics are mapped to a data frame. If you have only one line of text you want to appear on the plot, you should use annotate(geom="text"...), which is used when you do not want to map any aesthetics to a data frame.
I am trying to replicate the bar plot as shown bellow.
Here is an example of the data frame. Where the y variable is tasa and the x variable is year, and the number showed in the text of each x tick label is inscripciones.
df <- structure(list(year = c("2018", "2019"), inscripciones = c(3038910, 3680696), tasa = c(88.9528707645112, 104.692208214133)), class = c("tbl_df", "tbl", "data.frame"), row.names = c(NA, -2L))
p <- ggplot(data = df, aes(x = year, y = tasa)) +
geom_bar(width = 0.4, stat = "identity", fill="orange")+
geom_text(aes(year, tasa + 5, label = round(tasa,2), fill = NULL), size=4)+
labs(x = NULL, y = NULL)+
scale_y_continuous(breaks = seq(0, 110, by = 10))+
theme_bw()
How can I add these long text including information from the dataframe to the x tick labels?
Firstly, your data & plot combination are not reproducible. I renamed annoh as year then create the plot p.
Then,scale_x_discrete with "\n" strings works when you want to skip lines;
long_text_1 <- 'Gün, senden ışık alsa\n da bir renge bürünse;\n
Ay, secde edip çehrene,\n yerlerde sürünse;\n
Her şey silinip\n kayboluyorken nazarımdan,\n
Yalnız o yeşil\n gözlerinin nuru görünse...'
long_text_2 <- 'Ruhun mu ateş,\nyoksa o gözler mi alevden?\n
Bilmem bu yanardağ\n ne biçim korla tutuştu?\n
Pervane olan kendini\n gizler mi hiç alevden?\n
Sen istedin ondan bu\n gönül zorla tutuştu.'
p <- ggplot(data = df, aes(x = year, y = tasa)) +
geom_bar(width = 0.4, stat = "identity", fill="orange")+
geom_text(aes(year, tasa + 5, label = round(tasa,2), fill = NULL), size=4)+
labs(x = NULL, y = NULL)+
scale_y_continuous(breaks = seq(0, 110, by = 10))+
theme_bw()+
scale_x_discrete(labels=c('2018'=long_text_1,'2019'=long_text_2))
I'm very new to R and I hope this question is still interesting enough. I have the following dataframe:
> dput(df)
structure(list(Proportion = c(0.491475825983558, 0.624947117938639,
0.284285973983444, 0.459936074937072, 0.438167575182789, 0.5923527,
0.269347638359089, 0.444195335296524, 0.472343382529259, 0.6119936,
0.280545311041942, 0.45582336843016), Lower = c(0.373501802431026,
0.506815311121949, 0.196793171052086, 0.344394223066228, 0.342020291619279,
0.4962054, 0.197239652248339, 0.347543569904938, 0.362690139261045,
0.5158463, 0.198654362934906, 0.347479674558168), Upper = c(0.610508712286318,
0.729864865043791, 0.39179224043653, 0.580031198686217, 0.539194328764963,
0.6885, 0.356122647401151, 0.545263076314964, 0.5847316572176,
0.7081409, 0.380178492952045, 0.56851602179505), Area = c("SNP",
"SNP", "LGCA", "LGCA", "SNP", "SNP", "LGCA", "LGCA", "SNP", "SNP",
"LGCA", "LGCA"), Time = c("Day", "Night", "Day", "Night", "Day",
"Night", "Day", "Night", "Day", "Night", "Day", "Night"), Collar = c(41361,
41361, 41361, 41361, 41365, 41365, 41365, 41365, 41366, 41366,
41366, 41366)), row.names = c(NA, -12L), class = c("tbl_df",
"tbl", "data.frame"))
For which I have created the following plot:
Using the script below:
dfnew <- df %>%
mutate(ymin = Proportion - Lower,
ymax = Proportion + Upper)
p <- ggplot(data = dfnew, aes(x = Time, y = Proportion, color=Area, group=Area)) +
geom_point(size = 6, stroke = 0, shape = 16,
position = position_dodge(width = 0.1))+
geom_errorbar(aes(ymin = Lower, ymax = Upper), width=0.1, size=1,
position = position_dodge(width = 0.1)) +
theme(axis.text=element_text(size=15),
axis.title=element_text(size=20)) +
scale_color_manual(values = c("SNP" = "coral",
"LGCA" = "darkgoldenrod2")) +
geom_line(size=1,linetype="dotted")
p
I would like plot different symbols (e.g. ∆, O, ◊) accounting for the different collars in df. Also, I would like these to be moved slightly (position_dodge) so that not all points are on top of each other.
How can I access a symbol library and implement it into my script?
Any help would be very appreciated!
If you map the shape within an aes() call you can vary the shapes and if you want specific shapes you can use scale_shape_manual() for example just like with the colors. The dodging within one group can be achieved by either using geom_jitter() or replacing position_dodge() with position_jitterdodge().
Unfortunately this messes with the errorbars.
EDIT: There is a fix for the error bars in this answer by Marcelo. I also included a way to connect the same symbols with the dotted line. This is easiest done by adding another grouping column to your data.
dfnew <- df %>%
mutate(ymin = Proportion - Lower,
ymax = Proportion + Upper,
linegroup = paste(Area, Collar))
set.seed(2)
myjit <- ggproto("fixJitter", PositionDodge,
width = 0.6,
dodge.width = 0,
jit = NULL,
compute_panel = function (self, data, params, scales)
{
#Generate Jitter if not yet
if(is.null(self$jit) ) {
self$jit <-jitter(rep(0, nrow(data)), amount=self$dodge.width)
}
data <- ggproto_parent(PositionDodge, self)$compute_panel(data, params, scales)
data$x <- data$x + self$jit
#For proper error extensions
if("xmin" %in% colnames(data)) data$xmin <- data$xmin + self$jit
if("xmax" %in% colnames(data)) data$xmax <- data$xmax + self$jit
data
} )
ggplot(data = dfnew, aes(x = Time, y = Proportion, color=Area, group=linegroup)) +
geom_point(aes(shape = as.character(Collar)), size = 6, stroke = 0,
position = myjit)+
geom_line(aes(group = linegroup),linetype = "dotted",size=1, position = myjit) +
theme(axis.text=element_text(size=15),
axis.title=element_text(size=20)) +
geom_errorbar(aes(ymin = Lower, ymax = Upper), width=0.3, size=1,
position = myjit) +
scale_color_manual(values = c("SNP" = "coral",
"LGCA" = "darkgoldenrod2"))
I have a dataframe which I've used to create a ggplot object faceted into three separate plots.
max_24h_lactate_cpet.long
First_24h_Lactate_Max, Lactate_Above_Threshold, Metric, Value
2.3, High, AT_VO2_mL.kg.min, 17.00
2.3, High, VO2_Peak, 84.07
2.3, High, AT_VE_VCO2, 35.00
In dput format:
dput(max_24h_lactate_cpet.long)
structure(list(First_24h_Lactate_Max = c(2.3, 2.3, 2.3), Lactate_Above_Threshold = structure(c(1L,
1L, 1L),
.Label = c("High", "Normal"), class = "factor"), Metric = structure(1:3, .Label = c("AT_VO2_mL.kg.min",
"VO2_Peak", "AT_VE_VCO2"), class = "factor"), Value = c(17, 84.07,
35)), .Names = c("First_24h_Lactate_Max", "Lactate_Above_Threshold",
"Metric", "Value"), row.names = c(44L, 192L, 340L), class = "data.frame")
I want to put geom_rect() objects on each of these facets, but with different ymin and ymax values for each plot.
Here's my current code:
max_24h_lac_vs_cpet <- ggplot(max_24h_lactate_cpet.long,
aes(x = max_24h_lactate_cpet.long$First_24h_Lactate_Max,
y = max_24h_lactate_cpet.long$Value))
max_24h_lac_vs_cpet + geom_point() +
facet_wrap( ~ Metric, scales="free_y") +
scale_color_brewer(palette="Set1") +
labs(x = "Max Lactate Value < 24h after surgery (mmol)",
y = "Test Metric Value") +
stat_smooth(method="lm") +
annotate("rect", xmin=-Inf, xmax=1.6, ymin=-Inf, ymax=Inf,alpha=0.1,fill="blue")
This gives the following plot:
I've got my thresholds (x and y limits for geom_rect() objects) in a separate dataframe as follows:
Metric xmin xmax ymin ymax
AT_VO2_mL.kg.min -Inf Inf -Inf 10.2
VO2_Peak -Inf Inf -Inf 75.0
AT_VE_VCO2 -Inf Inf 42 Inf
Dput code:
dput(thresholds)
structure(list(Metric = structure(c(2L, 3L, 1L), .Label = c("AT_VE_VCO2",
"AT_VO2_mL.kg.min", "VO2_Peak"), class = "factor"), xmin = c(-Inf,
-Inf, -Inf), xmax = c(Inf, Inf, Inf), ymin = c(-Inf, -Inf, 42
), ymax = c(10.2, 75, Inf)), .Names = c("Metric", "xmin", "xmax",
"ymin", "ymax"), class = "data.frame", row.names = c(NA, -3L))
And have added this code snippet to my ggplot call
+ geom_rect(data=thresholds$Metric, aes(xmin=xmin, xmax=xmax,
ymin=ymin, ymax=ymax,
alpha=0.1,fill="red"))
Which gives an error as follows:
Error: ggplot2 doesn't know how to deal with data of class factor
Using the following also gives an error:
+ geom_rect(data=thresholds, aes(xmin=xmin, xmax=xmax,
ymin=ymin, ymax=ymax,
alpha=0.1,fill="red"))
Error: Aesthetics must either be length one, or the same length as the
dataProblems:xmin, xmax, ymin, ymax
I've looked at examples on other questions, but am struggling to translate their answers to my own problem. Any help would be appreciated!
So you didn't provide us with labels, and only three rows of the first data set, so what follows is incomplete, but should demonstrate how to get the rect's working:
max_24h_lac_vs_cpet <- ggplot(max_24h_lactate_cpet.long,
aes(x = First_24h_Lactate_Max,
y = Value))
max_24h_lac_vs_cpet + geom_point() +
facet_wrap( ~ Metric, scales="free_y") +
scale_color_brewer(palette="Set1") +
labs(x = "Max Lactate Value < 24h after surgery (mmol)",
y = "Test Metric Value") +
stat_smooth(method="lm") +
geom_rect(data=thresholds, aes(x = NULL,y = NULL,xmin=xmin, xmax=xmax,
ymin=ymin, ymax=ymax,
alpha=0.1,fill="red"))
You were using $ in the first aes() call. Never do that. Then you need to un-map x and y in the geom_rect layer, since they are inherited from the top level ggplot call. The other option would be to use inherit.aes = FALSE.