How to change time-order on x-axis? - r

I have a question to this specific code:
ggplot(MAGS)+
geom_col(aes(x = Photo.time#hour + Photo.time#minute/60, y = Number.of.Animals), lwd = 1) + ylab("total amount") +
scale_x_continuous(breaks = seq(0,24,4), name = "time", labels = c( "0:00", "4:00", "8:00", "12:00", "16:00", "20:00", "23:59")) +
theme_bw() + theme_classic()
scale_y_continuous(breaks = seq(0,10,2), name = "total amount", labels = c( "o","2","4","6","8","10"))
With this code I created the attached plot. This plot is okay but I guess it would look better if I changed the x axis so that it starts with 12:00pm, has 00:00am in the middle and ends with 11:59am. Kind of like in the attached plot but flipped. The data set comes from a nocturnal animal with high activity around midnight so it would be better to have 00:00 in the center of the x axis.
I tried several things but i always ended up with a mess. I can't figure out where my mistake is.
Thank you very much for helping :)
I tried several things to rearrange the x axis but I can't find the problem.

I'd suggest making a helper column that is ordered the way you want -- in this case I have added 24 hours to the first 12 hours of the day, to make hours 0:12 appear in hours 24:36, and then adjusting the labeling accordingly.
df1 <- data.frame(x = seq(0, 24 - 1/60, 1/60), y = 1:1440)
df1$x_order = df1$x + ifelse(df1$x < 12, 24, 0)
ggplot(df1, aes(x_order, y)) +
geom_col() +
scale_x_continuous(breaks = 12 + seq(0,24,4), name = "time",
labels = c("12:00", "16:00", "20:00", "00:00am", "4:00", "8:00", "12:00"))
EDIT - Based on the sample data you added in a comment, I've made some fake data that shows the overall pattern you have in your full data:
structure(list(Photo.time = new("Period",
.Data = c(51, 52, 54, 55, 56, 58, 0, 58, 56, 57),
year = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
month = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
day = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
hour = c(1, 2, 3, 4, 5, 6, 7, 12, 15, 20),
minute = c(48, 48, 48, 49, 49, 49, 58, 49, 0, 0)),
Number.of.Animals = c(10L, 8L, 6L, 5L, 2L, 1L, 0L, 2L, 6L, 10L)),
class = "data.frame", row.names = c(NA, 10L)) |>
ggplot() +
geom_col(aes(x = Photo.time#hour + Photo.time#minute/60, y = Number.of.Animals), lwd = 1) + ylab("total amount") +
scale_x_continuous(breaks = seq(0,24,4), name = "time", labels = c( "0:00", "4:00", "8:00", "12:00", "16:00", "20:00", "23:59")) +
theme_bw() + theme_classic()
I had trouble manipulating your time data, so I converted to decimal hours and applied my adjustment from above:
structure(list(Photo.time = new("Period", .Data = c(51, 52, 54, 55, 56, 58, 0, 58, 56, 57), year = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), month = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), day = c(0, 0, 0, 0, 0, 0, 0, 0, 0, 0), hour = c(1, 2, 3, 4, 5, 6, 7, 12, 15, 20), minute = c(48, 15, 48, 30, 49, 49, 58, 49, 0, 0)), Number.of.Animals = c(10L, 8L, 6L, 5L, 2L, 1L, 0L, 2L, 6L, 10L)), class = "data.frame", row.names = c(NA, 10L)) |>
mutate(time_hr_dec = as.numeric(Photo.time)/(60*60),
time_hr_dec2 = time_hr_dec + ifelse(time_hr_dec < 12, 24, 0)) |>
ggplot() +
geom_col(aes(x = time_hr_dec2, y = Number.of.Animals), lwd = 1) + ylab("total amount") +
scale_x_continuous(breaks = 12 + seq(0,24,4), name = "time",
labels = c("12:00", "16:00", "20:00", "00:00am", "4:00", "8:00", "12:00")) +
theme_bw() + theme_classic()
Yay, look! It has the expected shape and labels.

Related

labeling different lines in ggplot

My apologies for the second question
I wish to label my lines in my plot
I would like for the first line (y=launches) to be named "worldwide" and the second line (y=US) to be named US visibly in my plot
What is the best way to do this ?
plot1 <- ggplot()+
geom_line(data=dataplot,mapping = aes(x = date, y = launches, group=1) ) +
geom_line(data=dataplot,mapping = aes(x = date, y = US, group=1), colour="blue" )+
ggtitle("Kickstarter")+
labs(y= "Newly launched projects", x = "date") +
scale_x_date(date_breaks = "1 month")
plot1`
structure(list(date = c("2021-01-01", "2021-01-02", "2021-01-03",
"2021-01-04", "2021-01-05", "2021-01-06"), launches = c(4, 0,
0, 0, 8, 4), pledged = c(50278.64, 0, 0, 0, 366279.590415302,
172073.0471292), backers = c(2880, 0, 0, 0, 6588, 3528), total_goal = c(24000,
0, 0, 0, 148000, 60000), mean_goal = c(6000, 0, 0, 0, 18500,
15000), US = c(4, 0, 0, 0, 4, 0), `number of success` = c(4,
0, 0, 0, 8, 4), duration_days = c(30, 0, 0, 0, 31, 30), Twitter = c(1324L,
1548L, 1297L, 1585L, 1636L, 1583L), replies = c(882L, 1252L,
910L, 1018L, 810L, 1000L), likes = c(22859L, 24375L, 17854L,
20341L, 19521L, 19401L), retweets = c(8621L, 8239L, 6141L, 6728L,
6938L, 6842L)), row.names = c(NA, 6L), class = "data.frame")

How to add a frequency or number on scalebar of stacked barplot using geom_text?

I'm a newbie for using Rstudio, so I've some problems I want to ask.
I want to make my scalebar for species composition in 10 sites, and add the number inside the scalebar.
The result like this.
I want to put the frequency number of species composition inside the scale bar. I've been tried to put code of geom_text, but the result is not appropriate at all.
I hope there's an answer to fix this. Thank you so much.
Here is my data, also the coding that I run in R.
data <- as.matrix(data.frame(Bng = c(0, 0, 0, 41, 0, 9, 6, 25, 11, 2, 5, 7),
Krs = c(0, 25, 0, 82, 0, 0, 0, 0, 23, 0, 0, 0),
Bny = c(0, 0, 0, 0, 0, 0, 0, 23, 16, 0, 10, 0),
Kmb = c(1, 0, 0, 0, 20, 0, 0, 25, 8, 1, 0, 0),
Sgk = c(0, 0, 0, 18, 0, 2, 0, 11, 0, 0, 0, 0),
Lwb = c(1, 0, 2, 73, 0, 5, 0, 7, 5, 0, 0, 0),
Lws = c(0, 0, 0, 4, 0, 0, 0, 4, 0, 4, 1, 0),
Krp = c(0, 0, 0, 115, 0, 0, 2, 0, 2, 0, 0, 0),
Hrt = c(4, 0, 0, 0, 2, 22, 0, 7, 4, 2, 3, 0),
Gmb = c(0, 2, 0, 42, 2, 0, 0, 1, 6, 4, 3, 0)))
rownames(data) <- c("Cbr", "Csx", "Rax", "Hdd", "Hlv", "Mst", "Mps", "Mbr", "Rfs", "Rbn", "Rct", "Rps")
data
barplot(data)
barplot(prop.table(data, 2))```
library(reshape2)
data_long <- as.data.frame(data)
data_long$subgroup <- rownames(data_long)
data_long <- melt(data_long, id.vars = "subgroup")
library(ggplot2)
ggp <- ggplot(data_long,
aes(x = variable,
y = value,
fill = subgroup)) +
geom_bar(position = "fill", stat = "identity")+
theme_bw()+
scale_fill_grey()
ggp
ggp +
scale_y_continuous(labels = scales::percent_format())
You may try
library(dplyr)
data_long %>%
group_by(subgroup) %>%
mutate(key = sum(value),
value = value/sum(value)
) %>%
filter(value != 0) %>%
ggplot(aes(x = variable,
y = value,
fill = subgroup)) +
geom_bar(position = "fill", stat = "identity")+
theme_bw()+
scale_fill_grey() +
scale_y_continuous(labels = scales::percent_format()) +
geom_text(aes(label = value * key), position = position_fill(vjust = .5))

ggplot2 Reorder Data that is in minutes:seconds Format

The first five entries (out of twenty) of my dataset:
>head(data)
Name SDC
<chr> <Period>
1 Feuerman 1M 37S
2 Solis 1M 52S
3 Osborne 1M 47S
4 Frizzell 1M 58S
5 Moran 1M 59S
Also:
> dput(head(data))
structure(list(Name = c("Feuerman", "Solis", "Osborne", "Frizzell",
"Moran", "Seth"), Deadlift = c(320, 250, 340, 250, 250, 200),
Medicine_Ball = c(11.6, 8.8, 12.5, 9.2, 9.7, 9.1), HRP = c(46,
39, 36, 33, 42, 31), SDC = new("Period", .Data = c(37, 52,
47, 58, 59, 15), year = c(0, 0, 0, 0, 0, 0), month = c(0,
0, 0, 0, 0, 0), day = c(0, 0, 0, 0, 0, 0), hour = c(0, 0,
0, 0, 0, 0), minute = c(1, 1, 1, 1, 1, 2)), Leg_Tuck = c(20,
13, 4, 10, 13, 13), Run = new("Period", .Data = c(48, 59,
10, 53, 0, 29), year = c(0, 0, 0, 0, 0, 0), month = c(0,
0, 0, 0, 0, 0), day = c(0, 0, 0, 0, 0, 0), hour = c(0, 0,
0, 0, 0, 0), minute = c(13, 12, 17, 16, 0, 16)), Total = c(570,
508, 513, 470, 410, 452), Pass_Fail = structure(c(1L, 1L,
2L, 1L, 2L, 1L), .Label = c("Pass", "Fail"), class = "factor"),
Date = structure(c(18522, 18522, 18522, 18522, 18522, 18522
), class = "Date")), row.names = c(NA, -6L), class = c("tbl_df",
"tbl", "data.frame"))
As you can see, SDC is in minutes:seconds format. I achieved this using ms(data$SDC) to change the column type. I am trying to create a plot using geom_col that orders SDC from lowest to highest times. I am facing two problems:
When using the reorder command, the times are not properly reordered (see plot below).
The axes are being formatted by hour:minute:second but I want it to be formatted in only minute:second format (also see plot below).
Here is my code to generate the plot:
ggplot(data=data,
aes(x=reorder(Name, -SDC), y=SDC, fill=Pass_Fail)) +
scale_y_time(limits=c(0,200)) +
scale_fill_manual(values=c('#00BFC4', '#F8766D')) +
labs(x='Soldier', y='Sprint Drag Carry Time', fill='Passed/Failed ACFT', title='Sprint Drag Carry Scores') +
geom_col() +
geom_text(size=3, aes(label = SDC), hjust=-0.04) +
coord_flip() +
theme_classic()
It produces the following plot:
As you can see, the reordering is incorrect and the axes are not formatted the way I want them to be. Thanks in advance for your help.
I think reorder have trouble working with Period object. We can arrange the factor levels according to the value of SDC to get bars in increasing orders.
We can pass custom function for y-axis to get only minutes and seconds in labels.
library(tidyverse)
data %>%
arrange(SDC) %>%
mutate(Name = factor(Name, levels = unique(Name))) %>%
ggplot() + aes(x=Name, y=SDC, fill=Pass_Fail) +
scale_y_time(limits=c(0,200),
labels = function(x) sprintf('%02s:%02s', minute(x),second(x))) +
scale_fill_manual(values=c('#00BFC4', '#F8766D')) +
labs(x='Soldier', y='Sprint Drag Carry Time',
fill='Passed/Failed ACFT', title='Sprint Drag Carry Scores') +
geom_col() +
geom_text(size=3, aes(label = SDC), hjust=-0.04) +
coord_flip() +
theme_classic()

ggplot2: how do I add a second plot line

Ok,
[R3.4.2 + ggplot2]
Using the data example listed below, how do I add a second data plot? I tried this example which I found on this site;
library(ggplot2]
** This is part of the origanl code ****
rpt<-read.csv(file="rpt.csv,header=T)
rpt1<-read.csv(file="rpt1.csv,header=T)
*** code starts here *****
ggplot(rpt,aes(JulianDate,w)) + geom_line(aes(color="First line")) +
geom_line(data=rpt1, aes(color="Second line")) + labs(color="Legend text")
The first plot has x=rpt$JulianDate, y=rpt1$w; and the second plot has x1= rpt1$JDAy and y2=rpt1$wolf)
The data (use dget(_) to read it):
structure(list(
JDay = c(57023, 57024, 57027, 57028, 57029, 57031, 57032, 57035, 57037),
Obs = c(1, 1, 1, 1, 1, 1, 1, 1, 1),
w = c(71, 105, 64, 44, 45, 38, 66, 49, 28),
WStd = c(0, 0, 0, 0, 0, 0, 0, 0, 0),
wolf = c(91.59, 135.45, 82.56, 56.76, 58.05, 49.02, 85.14, 63.21, 36.12),
Adj = c(0, 0, 0, 0, 0, 0, 0, 0, 0)),
.Names = c("JDay", "Obs", "w", "WStd", "wolf", "Adj"),
class = "data.frame",
row.names = c(NA, -9L))
In your comment, you say that rpt and rpt1 have the same data. Therefore, I think this is what you are asking for
library(ggplot2)
ggplot(rpt, aes(x=JDay)) +
geom_line(aes(y=w, color="First line")) +
geom_line(aes(y=wolf, color="Second line")) +
labs(color="Legend text")

How to customize the tooltip of ggplotly?

I have tried to follow different answers here but none worked. I went through the plotly official documentation and came up with following:
Data
Following is a sample of the data set:
> dput(head(df))
structure(list(ID = c(-1, -1, -1, -1, -1, -1), spacing.ft = c(0,
0, 0, 0, 0, 0), gap.s = c(0, 0, 0, 0, 0, 0), frspacing.ft = c(0,
0, 0, 0, 0, 0), TTC = c(0, 0, 0, 0, 0, 0), LV.vel.fps = c(0,
0, 0, 0, 0, 0), x = c(0, 0, 0, 0, 0, 0), y = c(0, 0, 0, 0, 0,
0), z = c(0, 0, 0, 0, 0, 0), frames = 29373:29378, df16 = c(6L,
6L, 6L, 6L, 6L, 6L), ADO.name = structure(c(NA_integer_, NA_integer_,
NA_integer_, NA_integer_, NA_integer_, NA_integer_), .Label = c("BlueT5",
"ghtTFrei10", "ilT6Carg", "owT8Yell", "CargoT4", "MoveT12", "RaceT11",
"RedT1", "SemiT3", "StarT7", "WhiteT2", "artTWalm9"), class = "factor"),
speed.fps.ED = c(33.25, 33.4, 33.55, 33.7, 33.84, 33.99),
deltaV.fps = c(33.25, 33.4, 33.55, 33.7, 33.84, 33.99)), .Names = c("ID",
"spacing.ft", "gap.s", "frspacing.ft", "TTC", "LV.vel.fps", "x",
"y", "z", "frames", "df16", "ADO.name", "speed.fps.ED", "deltaV.fps"
), row.names = c(NA, 6L), class = "data.frame")
What I want to do:
I want to customize the tooltip to add speed, speed.fps.ED. I tried following:
library(ggplot2)
library(plotly)
mt.plot <- ggplot() +
geom_point(data = df,
mapping = aes(x = deltaV.fps, y = frspacing.ft, color = ADO.name))
# Build the ggplot:
p <- plotly_build(mt.plot)
# Change the tooltip:
p$data[[1]]$text <- paste("ED.speed = ", df$speed.fps.ED)
p$filename <- 'test'
r <- plotly_POST(p)
knit_print.plotly(r, options=list())
You can see the resulting plot here: Plot.
Problem
The problem is that the third element in the tooltip is displayed only for 1 ADO.name i.e. BlueT5. I want it to be visible for all ADO.names. What is the problem here?
You can add speed.fps.ED to the ggplot aesthetic, as in:
geom_point(data = df,
aes(x = deltaV.fps, y = frspacing.ft, color = ADO.name, label = speed.fps.ED))
See also: how to choose variable to display in tooltip when using ggplotly?

Resources