R - using ggplot for line chart - no line showing - r

I'm using ggplot and geom_line but there is no line showing up.
I used this command:
library(ggplot2)
ggplot(campaigns, aes(x=Send.Time, y=Open.Rate, color='red')) + geom_line()
Please see screenshot below

You should remove "%" from the string and convert into numeric. Please see the code below:
# Simulation
library(lubridate)
library(dplyr)
campaigns <- data.frame(
Send.Time = c("5/30/17", "6/1/17", "6/1/17", "6/6/17", "6/8/17", "6/15/17"),
Open.Rate = c("33.40%", "9.14%", "29.64%", "24.90%", "8.07%", "32.44%")
)
# convert to numeric
campaigns <- campaigns %>% mutate(Open.Rate = as.numeric(gsub("%", "", as.character(Open.Rate))))
# plot
campaigns %>% ggplot(aes(x = as.numeric(Send.Time), y = Open.Rate), colour = "red") +
geom_line() +
scale_x_continuous(labels = campaigns$Send.Time, breaks = seq_along(campaigns$Send.Time)) +
geom_point() +
xlab("Session date")
Output:

Related

ggplot not rendering plot correctly

I have used a simple CSV table and made a plot with the desired colors and dots, but I cannot find the solution to connect the dots with a line.
#----Import data----#
DS <- read_csv("https://raw.githubusercontent.com/Iqbalpr/Tugas-Kuliah--UIN/main/Data%20Skripsi%20Gender%20%2B%20Negara%20(CSV).csv")
View(DS)
ncol(DS)
nrow(DS)
#----Check and convert column type----#
str(DS) # Check Column
DS$ID <- as.factor(DS$ID )
DS$Gender <- as.factor(DS$Gender)
DS$Tahun <- as.integer(DS$Tahun)
DS$Inflasi <- as.numeric(DS$Inflasi)
DS$Pengangguran <- as.numeric(DS$Pengangguran)
DS$`GDP growth rate` <- as.numeric(DS$`GDP growth rate`)
DS$`GDP per Capita` <- as.numeric(DS$`GDP per Capita`)
str(DS) # Check Column Again
#----Plot----#
p <- ggplot(DS) + aes(x = Tahun, y = AHH, group = Negara, color = Negara) + geom_point()
p
enter image description here
Now I want the dots connected with the same color as the dots and I use this code:
p <- ggplot(DS) + aes(x = Tahun, y = AHH, group = Negara, color = Negara) + geom_point() + geom_line()
p
but I get a very strange line like this :
enter image description here
What am I doing wrong?
This happens because you have two values per country because of your Gender column which will result in the graph you have. An option is to use facet_wrap to plot it for each Gender like this:
library(ggplot2)
p <- ggplot(DS) +
aes(x = Tahun, y = AHH, group = Negara, color = Negara) +
geom_point() +
geom_line() +
facet_wrap(~Gender)
p
Output:

How Do I Sum or Count a Factor Variable in R (for use in stacked bar chart)?

I want to create a stacked bar chart in R such that it shows the sum of levels of a feature over time. The feature is of type factor, "char", with levels A, B, H, N, P, U, W. Date feature is type date.
Example data from "chart_df":
char
date
w
2022-04-09
w
2022-04-07
b
2022-04-06
n
2022-04-05
b
2022-04-03
b
2022-04-03
I'm a total beginner. I've tried y= count(), sum(), summarize() with no luck. I've even tried to group by month in hopes that cleaned it up, but it didn't help. I've used this as my guide: https://r-graph-gallery.com/136-stacked-area-chart.html
I can't figure out how to sum the number of chars for a given date(for ex, "b" would have 2 for 2022-04-03). Below is where I'm at so far but it looks awful:
enter image description here
library(tidyverse)
library(plotly)
library(ggplot2)
library(viridis)
library(hrbrthemes)
p <- chart_df %>%
ggplot( aes(x=date, y = frequency(char), fill=char, text=char)) +
geom_area() +
scale_fill_viridis(discrete = TRUE) +
theme(legend.position="none") +
theme_ipsum() +
theme(legend.position="top")
# Turn it interactive
p <- ggplotly(p, tooltip="text")
p
I'd like to create a nice, clear and understandable stacked bar chart showing amounts of char for each day over time. Thank you.
One option would be to use stat="count" in geom_area (and drop the y aes):
library(ggplot2)
library(plotly)
library(viridis)
library(hrbrthemes)
chart_df$date <- as.Date(chart_df$date)
p <- ggplot(chart_df, aes(x = date, fill = char, text = char)) +
geom_area(stat = "count") +
scale_fill_viridis(discrete = TRUE) +
theme(legend.position = "none") +
theme_ipsum() +
theme(legend.position = "top")
ggplotly()
Or as a second option you could compute the counts manually using e.g. dplyr::count:
library(dplyr)
chart_df_agg <- chart_df %>%
count(date, char, name = "count")
p <- ggplot(chart_df_agg, aes(x = date, y = count, fill = char, text = char)) +
geom_area() +
scale_fill_viridis(discrete = TRUE) +
theme(legend.position = "none") +
theme_ipsum() +
theme(legend.position = "top")
ggplotly()
DATA
chart_df <- data.frame(
stringsAsFactors = FALSE,
char = c("w", "w", "b", "n", "b", "b"),
date = c(
"2022-04-09", "2022-04-07",
"2022-04-06", "2022-04-05", "2022-04-03", "2022-04-03"
)
)
Thanks, everyone. The " y = count" tip was super helpful.
I figured it out using the lubridate library (good for date stuffs):
s <- chart_df_agg %>%
ggplot(aes(x= chart_df_agg$`year(chart_df$date)`, y = char_count,
fill=char, text=char)) +
geom_area(size= 0.1, colour="black") +
scale_fill_viridis(discrete = TRUE) +
theme(legend.position="none") +
theme_ipsum() +
theme(legend.position="top")
# Turn it interactive
s <- ggplotly(s, tooltip="text")
s

Produce a time line plot with specific draw

Inserting this data:
df <- data.frame(year = c(2011,2012,2013,2014,2015,2016,2017,2018), value = c(337,423,551,661,846,1387,2222,3580))
How is it possible to produce a line plot like this using the df data?
enter image description here
Here is an example. Text placement relative to the points can be a bit finnicky.
library(ggplot2)
df <- data.frame(year = c(2011,2012,2013,2014,2015,2016,2017,2018),
value = c(337,423,551,661,846,1387,2222,3580))
ggplot(df, aes(year, value)) +
geom_point() +
geom_line() +
geom_text(aes(label = value, y = (value - 50)*0.9))

Fill area under time series based on factor value

I am trying to fill the area under a time series line based on a factor value of 0 and 1. The area should only be filled if the value is equal to 1.
I have managed to colour code the time series line based on the factor value with the following code:
install.packages("scales")
library("scales")
library("ggplot2")
ggplot(plot.timeseries) +
geom_line(aes(x = Date, y = Price, color = Index, group = 1)) +
scale_x_date(labels = date_format("%Y"), breaks = date_breaks("years")) +
scale_colour_manual(values = c("red3", "green3"))
This provides the following graph:
I have also tried this:
ggplot(plot.timeseries, aes(x=Date, y = Price, fill=Index)) +
geom_area(alpha=0.6) +
theme_classic() +
scale_fill_manual(values=c("#999999", "#32CD32"))
which comes out as a complete mess:
Ideally the final result should look like plot1 where the parts of the line in green are filled.
The time series data can be accessed here:
https://drive.google.com/file/d/1qWsuJk41_fJZktLCAZSgfGvoDLqTt-jk/view?usp=sharing
Any help would be greatly appreciated!
Okay, here is what I did to get the graph shown below if that is what you want.
# -------------------------------------------------------------------------
# load required packages #
library(scales)
library("ggplot2")
library(dplyr)
# -------------------------------------------------------------------------
# load the data to a df #
plot.timeseries <- get(load("TimeSeries_Data.RData"))
# -------------------------------------------------------------------------
# transform the data (my_fill_color will have green and NA values)
my_object <- plot.timeseries %>%
select(Price, Index, Date) %>%
mutate(Index_ord_factor = factor(Index, levels = unique(Index), ordered=TRUE),
my_fill_color = case_when(
Index_ord_factor > 0 ~ "green" # ordered factor enables the '>' operation
))
# -------------------------------------------------------------------------
# Plot your graph using the transformed data
ggplot(my_object, mapping = aes(x=Date, y=Price)) +
geom_line(aes(color = Index, group = 1))+
geom_col(fill =my_object$my_fill_color, width = 1)
# -------------------------------------------------------------------------
Let me know if you need elaboration to understand the script. Attached is the output in my end.
For those that are interested I also received this alternative solution from Erik Chacon.
You can view his tutorial here for a better understanding of the ggplot2 extension he designed, which is used in this solution.
# Installing and loading necessary packages
install.packages("remotes")
remotes::install_github("ErickChacon/mbsi")
library(mbsi)
library(ggplot2)
load("timeseries.RData")
#converting factor to numeric
plot.timeseries$Index <- as.numeric(levels(plot.timeseries$Index))[plot.timeseries$Index]
ggplot(plot.timeseries, aes(Date, Price)) +
geom_line() +
stat_events(aes(event = I(1 * (Index > 0)), fill = "Index"),
threshold = min(plot.timeseries$Price),
fill = "green", alpha = 0.3)

Change x-axis names in ggplot

I am not very good in R, and need some help.
My ggplot has a lot of dates(in the x-axis) so you can't actually see the dates, and I want to change it to months to give a better overview of the plot.
For example to something like this in the link:
Display the x-axis on ggplot as month only in R
This is the script I'm using:
r <- read.csv("xxdive.csv", header = T, sep = ";")
names(r) <- c("Date", "Number")
r <- data.frame(r)
r$Date <- factor(r$Date, ordered = T)
r[1:2, ]
Date Number
16.02.2015 97
17.02.2015 47
library(tidyverse)
ggplot(r, aes(Date, Number)) +
theme_light() +
ggtitle("16.02.15-10.02.16") +
ylab("Dives") +
geom_line(aes(group = 1), color = "blue")
This shows what kind of data I have.
I have tried using scale etc, but I can't make it work..
I hope this was understandable, and that someone can help me!! :)
I would convert column Date to data type Date
r$Date <- as.Date(r$Date, "%d.%m.%Y");
instead of converting it to data type factor.
r$Date <- factor(r$Date, ordered = T);
It's a little tricky without a working example, but try this.
install.packages("tidyverse")
library(tidyverse)
r <- read_delim("xxdive.csv", ";", col_types = list(col_date(), col_integer()))
names(r) <- c("Date", "Number")
ggplot(r, aes(Date, Number)) +
geom_line(aes(group = 1), color = "blue") +
scale_x_date(date_breaks = "1 month") +
ylab("Dives") +
ggtitle("16.02.15-10.02.16") +
theme_light()

Resources