ordering of ggplot not working with factors - r

I have created a vector with the order of a dot plot mentioned but it doesn't plot in that order/ Thanks for the suggestions.
order <- sav %>%
filter(Subject == "Food") %>%
arrange(desc(Percentage)) %>%
select(Location) %>%
unlist() %>%
unname()
order <- replace(order, c(1, 8), order[c(8, 1)])
sav %>%
ggplot(aes(x = factor(Location, levels = order), y = Percentage,
color = Subject))+
geom_point(data = filter(sav, Location != "IRELAND"),
size = 4, position = position_dodge(0.5))+
geom_point(data = filter(sav, Location == "IRELAND"),
size = 6, position = position_dodge(1))+
geom_linerange(data = filter(sav, Location == "IRELAND"),
aes(ymin = 0, ymax = Percentage),
position = position_dodge(1),
linetype = "dotdash") +
geom_linerange(data = filter(sav, Location != "IRELAND"),
aes(ymin = 0, ymax = Percentage),
position = position_dodge(0.5), linetype = "dotdash") +
coord_flip()+
ggtitle(label = "Increase in inflation (by CPI) in Ireland compared to OECD and other countries in OECD")+
xlab("Countries --> ") +
ylab("Increase in CPI by % -->")+
scale_y_continuous(breaks = round(seq(0, 20, by = 1),1))+
scale_color_manual(name = "Type of Items",
labels = c("Food", "Total", "Excluding food and energy"),
values=c(unname(colorblind_colors[2]),
unname(colorblind_colors[3]),
unname(colorblind_colors[4])))+
theme(panel.grid.major.x = element_line(linewidth =.01, color="black"),
panel.grid.major.y = element_blank(),
legend.position = "top"
)
> dput(order)
c("IRELAND", "NETHERLANDS", "SPAIN", "OECD", "ITALY", "FRANCE",
"UNITED STATES", "GERMANY", "CANADA")
> dput(sav)
structure(list(Location = c("CANADA", "CANADA", "FRANCE", "FRANCE",
"GERMANY", "GERMANY", "IRELAND", "IRELAND", "ITALY", "ITALY",
"NETHERLANDS", "NETHERLANDS", "SPAIN", "SPAIN", "UNITED STATES",
"UNITED STATES", "OECD", "OECD", "CANADA", "ITALY", "SPAIN",
"FRANCE", "IRELAND", "UNITED STATES", "NETHERLANDS", "OECD",
"GERMANY"), Subject = c("Food", "Total", "Food", "Total", "Food",
"Total", "Food", "Total", "Food", "Total", "Food", "Total", "Food",
"Total", "Food", "Total", "Food", "Total", "Total_Minus_Food_Energy",
"Total_Minus_Food_Energy", "Total_Minus_Food_Energy", "Total_Minus_Food_Energy",
"Total_Minus_Food_Energy", "Total_Minus_Food_Energy", "Total_Minus_Food_Energy",
"Total_Minus_Food_Energy", "Total_Minus_Food_Energy"), Frequency = c("Monthly",
"Monthly", "Monthly", "Monthly", "Monthly", "Monthly", "Monthly",
"Monthly", "Monthly", "Monthly", "Monthly", "Monthly", "Monthly",
"Monthly", "Monthly", "Monthly", "Monthly", "Monthly", "Monthly",
"Monthly", "Monthly", "Monthly", "Monthly", "Monthly", "Monthly",
"Monthly", "Monthly"), Time = c("2022-12", "2022-12", "2022-12",
"2022-12", "2022-12", "2022-12", "2022-12", "2022-12", "2022-12",
"2022-12", "2022-12", "2022-12", "2022-12", "2022-12", "2022-12",
"2022-12", "2022-12", "2022-12", "2022-12", "2022-12", "2022-12",
"2022-12", "2022-12", "2022-12", "2022-12", "2022-12", "2022-12"
), Percentage = c(11.02015, 6.319445, 12.86678, 5.850718, 19.75631,
8.550855, 11.74636, 8.224299, 13.14815, 11.63227, 16.7983, 9.586879,
15.68565, 5.70769, 11.88275, 6.454401, 15.60381, 9.438622, 5.58275,
4.469475, 4.442303, 3.36004, 4.999758, 5.707835, 6.034873, 7.221961,
5.05511)), class = "data.frame", row.names = c(NA, -27L))

A couple of things:
The factors need to be in the data that ggplot sees at every geom, but while you're setting factor(Location,levels=order) in the first mapping, none of the data= arguments is using the same data.
For this, I generally prefer factorizing the data up-front, and using ~-style "functions" for data=.
Not sure exactly why this is the case, but it still doesn't work ... but if the first call to geom_point uses mutate and replaces IRELAND's percentage values with NA, the levels are retained. Weird.
### I still don't have these :-)
colorblind_colors <- 1:4
sav %>%
mutate(Location = factor(Location, levels = order)) %>%
ggplot(aes(x = Location, y = Percentage, color = Subject)) +
geom_point(data = ~ mutate(., Percentage = if_else(Location == "Ireland", Percentage[NA], Percentage)),
size = 4, position = position_dodge(0.5), na.rm = TRUE) +
geom_point(data = ~ filter(., Location == "IRELAND"),
size = 6, position = position_dodge(1)) +
geom_linerange(data = ~ filter(., Location == "IRELAND"),
aes(ymin = 0, ymax = Percentage),
position = position_dodge(1),
linetype = "dotdash") +
geom_linerange(data = ~ filter(., Location != "IRELAND"),
aes(ymin = 0, ymax = Percentage),
position = position_dodge(0.5), linetype = "dotdash") +
coord_flip()+
ggtitle(label = "Increase in inflation (by CPI) in Ireland compared to OECD and other countries in OECD")+
xlab("Countries --> ") +
ylab("Increase in CPI by % -->")+
scale_y_continuous(breaks = round(seq(0, 20, by = 1),1))+
scale_color_manual(name = "Type of Items",
labels = c("Food", "Total", "Excluding food and energy"),
values=c(unname(colorblind_colors[2]),
unname(colorblind_colors[3]),
unname(colorblind_colors[4])))+
theme(panel.grid.major.x = element_line(linewidth =.01, color="black"),
panel.grid.major.y = element_blank(),
legend.position = "top"
)

Related

How to create a double bar contrast plot using ggplot2

I am trying to replicate a plot using ggplot2 to show the performance between two soccer teams. I look for getting this plot:
I have the data df for that. This is the code I have been using:
library(ggplot2)
#Plot
ggplot(df,aes(x=type,y=value,fill=name))+
geom_bar(stat = 'identity')+
geom_text(aes(label=abs(value),hjust=1))+
coord_flip()
Which produces next result:
The result is far away from first plot.
The issues I face are next:
The scale is too large for some type values, so is not possible to see each measure with independent scale. I think a facet_grid() or facet_wrap() would solve this but it did not worked.
The values for type must go in the middle, but I do not know how to move the axis to middle.
The labels for each bar should be on top of each bar but when I adjust hjust one of them goes to the right place but the other is placed wrong.
Finally, in df there is column named logo which stores the flags of two teams, how I can add the flags for each team one at top right side and the other at top left side.
Many thanks. This is the data df.
#Data
df <- structure(list(type = c("Shots on Goal", "Shots off Goal", "Total Shots",
"Blocked Shots", "Shots insidebox", "Shots outsidebox", "Fouls",
"Corner Kicks", "Offsides", "Ball Possession % ", "Yellow Cards",
"Red Cards", "Goalkeeper Saves", "Total passes", "Passes accurate",
"Passes %", "Shots on Goal", "Shots off Goal", "Total Shots",
"Blocked Shots", "Shots insidebox", "Shots outsidebox", "Fouls",
"Corner Kicks", "Offsides", "Ball Possession % ", "Yellow Cards",
"Red Cards", "Goalkeeper Saves", "Total passes", "Passes accurate",
"Passes %"), value = c(7, 2, 13, 4, 10, 3, 9, 8, 2, 78, 0, 0,
1, 797, 716, 90, -3, -4, -8, -1, -6, -2, -14, 0, -2, -22, -2,
0, -1, -215, -142, -66), name = c("England", "England", "England",
"England", "England", "England", "England", "England", "England",
"England", "England", "England", "England", "England", "England",
"England", "Iran", "Iran", "Iran", "Iran", "Iran", "Iran", "Iran",
"Iran", "Iran", "Iran", "Iran", "Iran", "Iran", "Iran", "Iran",
"Iran"), logo = c("https://media.api-sports.io/football/teams/10.png",
"https://media.api-sports.io/football/teams/10.png", "https://media.api-sports.io/football/teams/10.png",
"https://media.api-sports.io/football/teams/10.png", "https://media.api-sports.io/football/teams/10.png",
"https://media.api-sports.io/football/teams/10.png", "https://media.api-sports.io/football/teams/10.png",
"https://media.api-sports.io/football/teams/10.png", "https://media.api-sports.io/football/teams/10.png",
"https://media.api-sports.io/football/teams/10.png", "https://media.api-sports.io/football/teams/10.png",
"https://media.api-sports.io/football/teams/10.png", "https://media.api-sports.io/football/teams/10.png",
"https://media.api-sports.io/football/teams/10.png", "https://media.api-sports.io/football/teams/10.png",
"https://media.api-sports.io/football/teams/10.png", "https://media.api-sports.io/football/teams/22.png",
"https://media.api-sports.io/football/teams/22.png", "https://media.api-sports.io/football/teams/22.png",
"https://media.api-sports.io/football/teams/22.png", "https://media.api-sports.io/football/teams/22.png",
"https://media.api-sports.io/football/teams/22.png", "https://media.api-sports.io/football/teams/22.png",
"https://media.api-sports.io/football/teams/22.png", "https://media.api-sports.io/football/teams/22.png",
"https://media.api-sports.io/football/teams/22.png", "https://media.api-sports.io/football/teams/22.png",
"https://media.api-sports.io/football/teams/22.png", "https://media.api-sports.io/football/teams/22.png",
"https://media.api-sports.io/football/teams/22.png", "https://media.api-sports.io/football/teams/22.png",
"https://media.api-sports.io/football/teams/22.png")), row.names = c(NA,
-32L), class = c("tbl_df", "tbl", "data.frame"))
Perhaps something like this?
library(tidyverse)
library(ggimage)
df %>%
group_by(type) %>%
mutate(tot = sum(abs(value)),
prop = value/tot) %>%
ggplot(aes(prop, type, color = name)) +
geom_linerange(aes(xmin = -1, xmax = 1), color = "gray95", linewidth = 3) +
geom_linerange(aes(xmin = prop, xmax = 0), linewidth = 3) +
scale_color_manual(values = c("#8ded05", "#00aaff")) +
geom_text(aes(label = type, x = 0), check_overlap = TRUE, nudge_y = 0.4,
color = "black") +
geom_text(aes(x = ifelse(name == "England", 1.05, -1.05),
label = abs(value)), color = "black") +
theme_void() +
scale_y_discrete(expand = c(0.1, 0)) +
annotate(geom = "text", x = c(-0.5, 0.5), y = c(17, 17),
label = c("Iran", "England"), size = 5) +
geom_image(data = data.frame(x = c(1, -1), y = 17,
image = unique(df$logo)),
aes(x, y, image = image), inherit.aes = FALSE)+
guides(color = guide_none())

How to make stacked bar chart using ggplot2? [duplicate]

This question already has answers here:
Create stacked barplot where each stack is scaled to sum to 100%
(5 answers)
Closed 10 months ago.
So I am having trouble making a stacked bar chart showing proportion of cases vs deaths.
This is the data:
df <- structure(list(Date = structure(c(19108, 19108, 19108, 19108,
19108, 19108, 19108, 19108, 19108, 19108), class = "Date"), Country = c("US",
"India", "Brazil", "France", "Germany", "United Kingdom", "Russia",
"Korea, South", "Italy", "Turkey"), Confirmed = c(81100599L,
43065496L, 30378061L, 28605614L, 24337394L, 22168390L, 17887152L,
17086626L, 16191323L, 15023662L), Recovered = c(0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L), Deaths = c(991940L, 523654L, 663108L,
146464L, 134489L, 174778L, 367692L, 22466L, 162927L, 98720L),
Active = c(80108659L, 42541842L, 29714953L, 28459150L, 24202905L,
21993612L, 17519460L, 17064160L, 16028396L, 14924942L)), row.names = c(163539L,
163431L, 163375L, 163414L, 163418L, 163537L, 163496L, 163444L,
163437L, 163533L), class = "data.frame")
and I want to generate something that looks like this except with proportions of deaths vs cases.
This is a modification of #Allan Cameron's answer with adding the percent label and some other different approaches:
library(tidyverse)
library(scales)
df %>%
rename_with(., ~str_replace_all(., 'top10.', '')) %>%
pivot_longer(
cols = -Country,
names_to = "Status",
values_to = "value",
values_transform = list(value = as.integer)
) %>%
mutate(Status = fct_rev(fct_infreq(Status))) %>%
group_by(Country) %>%
mutate(pct= prop.table(value) * 100) %>%
ggplot(aes(x= Country, y = pct, fill=Status)) +
geom_col(position = position_fill())+
scale_fill_manual(values = c("#ff34b3", "#4976ff")) +
scale_y_continuous(labels = scales::percent)+
ylab("Percentage") +
geom_text(aes(label=paste0(sprintf("%1.1f", pct),"%")),
position=position_fill(vjust = 0.1)) +
ggtitle("Your Title")
I had to use OCR to convert the image of your data into actual data I could use. It's far better to include your data as text for this reason.
The plot is not particularly informative because the percentages are low, and difficult to read, but in any case, you can do it like this:
library(tidyverse)
p <- df %>%
mutate(top10.Confirmed = top10.Confirmed - top10.Deaths,
top10.Country = factor(top10.Country, top10.Country)) %>%
rename(Country = top10.Country,
Survived = top10.Confirmed,
Died = top10.Deaths) %>%
pivot_longer(-Country, names_to = "Outcome", values_to = "Count") %>%
mutate(Outcome = factor(Outcome, c("Survived", "Died"))) %>%
ggplot(aes(Country, Count, fill = Outcome)) +
geom_col(position = "fill") +
scale_fill_manual(values = c("#4976ff", "#ff34b3")) +
scale_y_continuous(labels = scales::percent) +
labs(title = "Covid outcomes by country", y = "Percent")
p
To make it easier to read, you could zoom into the bottom:
p + coord_cartesian(ylim = c(0, 0.05))
Data in reproducible format
df <- structure(list(top10.Country = c("US", "India", "Brazil", "France",
"Germany", "United Kingdom", "Russia", "Korea, South", "Italy",
"Turkey"), top10.Confirmed = c(81100599L, 43065496L, 30378061L,
28605614L, 24337394L, 22168390L, 17887152L, 17086626L, 16191323L,
15023662L), top10.Deaths = c(991940L, 523654L, 663108L, 146464L,
134489L, 174778L, 367692L, 22466L, 162927L, 98720L)), class = "data.frame",
row.names = c("1", "2", "3", "4", "5", "6", "7", "8", "9", "10"))
df
#> top10.Country top10.Confirmed top10.Deaths
#> 1 US 81100599 991940
#> 2 India 43065496 523654
#> 3 Brazil 30378061 663108
#> 4 France 28605614 146464
#> 5 Germany 24337394 134489
#> 6 United Kingdom 22168390 174778
#> 7 Russia 17887152 367692
#> 8 Korea, South 17086626 22466
#> 9 Italy 16191323 162927
#> 10 Turkey 15023662 98720
Created on 2022-05-01 by the reprex package (v2.0.1)

R studio Barplot

I have the following dataframe:
structure(list(share.beer = c(0.277, 0.1376, 0.1194, 0.0769,
0.0539, 0.0361, 0.0361, 0.0351, 0.0313, 0.03, 0.0119, 0.0084,
0.007, 0.0069), country = c("Brazil", "China, mainland", "United States",
"Thailand", "Vietnam", "China, mainland", "China, mainland",
"China, mainland", "China, mainland", "Argentina", "Indonesia",
"China, mainland", "China, mainland", "India"), Beer = c("soyb",
"maiz", "soyb", "cass", "cass", "whea", "rape", "soyb", "rice",
"soyb", "cass", "cott", "swpo", "rape")), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -14L))
I want to create a barplot so that the beer type appears in the legend, the countries as y values while the share.beer are my values to be filled.
I have tried in various ways, including the following code, but I can't get the result I would like to. Here, for instance, I kept the variable "Beer""
df %>%
pivot_longer(cols = -Country, values_to = "Count", names_to = "Type") %>%
ggplot() +
geom_col(aes(x = reorder(Country, -Count), y = Count, fill = Beer))
However, I get an error
Can't combine share beer and Beer .
Any help?
You actually don't need the pivot_longer to create a suitable dataframe. You can use the following code:
library(tidyverse)
df %>%
ggplot() +
geom_col(aes(x = reorder(country, -share.beer), y = share.beer, fill = Beer)) +
xlab("Country") +
ylab("Share beer") +
coord_flip()
Output:

Why does the Shiny-app not react to user input

I am trying to build a web app in shiny that would allow for different user input and then plot graphs/output data tables accordingly. I am using WHO's data about suicide rates and there are two possible types of graphs: bar plot and line graph.
The user is given a choice between plotting the graph in which the x axis is either the age group (barplot) or year (line graph). They are also given the choice of plotting the graph separately for males and females and different countries as well.
The code below works fine for everything except when the user chooses x axis = year with gender = 'gender neutral'. The error says that the object rate is not found. However, the block of code which includes the object rate works perfectly fine in other places.
library(shiny)
library(dplyr)
library(ggplot2)
setwd("C:\\Users\\Lenovoi7\\Shrewsbury School\\IT\\Coursework")
who<-data.frame(read.csv("who.csv", stringsAsFactors = TRUE))
dput(head(who))
countries<-sort(unique(who$country))
countries<-union(countries, c("World"))
ui<-fluidPage(
titlePanel("Suicide statistics"),
sidebarLayout(
sidebarPanel(
selectInput(
inputId="x",
label="Please choose the x variable",
choices=c("",
"Age group"="age",
"Year"="year")),
conditionalPanel(
condition = "input.x == 'age' || input.x == 'year'",
selectInput(
inputId = "gender",
label = "Please specify the gender characteristics",
choices = c("", "Gender neutral" = "gender_neutral",
"Gender specific" = "gender_specific"),
selected = NULL),
#nested conditional panel
#only show this panel if the input is gender_specific
conditionalPanel(
condition = "input.gender == 'gender_specific'",
selectInput(
inputId = "country",
label = "Select a country:",
choices = countries,
selected = "Bosnia and Herzegovina")),
conditionalPanel(
condition = "input.gender == 'gender_neutral'",
selectInput(
inputId = "country",
label = "Select a country:",
choices = countries,
selected = "Bosnia and Herzegovina")))),
mainPanel(
plotOutput("graph")
)))
server <- function(input, output) {
x<-reactive({input$x})
gender<-reactive({input$gender})
country<-reactive({input$country})
output$graph <- renderPlot(
#x axis = age group
if (x()=="age"){
if (gender()=="gender_neutral"){
if (country()=="World"){
ggplot(data=who, aes(x=age)) + geom_bar(aes(weights=suicides_no), position="dodge")}
else {
#create a new subset of data that will be used??
who_subset<-subset(who, country == input$country)
ggplot(data=who_subset, aes(x=age)) + geom_bar(aes(weights=suicides_no))}}
else if (gender()=="gender_specific"){
if (country()=="World"){
ggplot(data=who, aes(x=age)) + geom_bar(aes(weights=suicides_no, fill=sex), position="dodge")}
else {
#create a new subset of data that will be used??
who_subset<-subset(who, country==input$country)
ggplot(data=who_subset, aes(x=age)) + geom_bar(aes(weights=suicides_no, fill=sex), position="dodge")}}}
else if (x()=="year"){
if (gender()=="gender_neutral"){
if (country()=="World"){
who_all <- who %>%
group_by(year) %>%
summarize(suicides_no = sum(suicides_no),
population = sum(population)) %>%
mutate(rate = 100000 * suicides_no/population)
ggplot() +
geom_line(data = who_all, aes(year, rate))
}
else {
who_subset<-subset(who, country==input$country)
who_sub_sex <- who_subset %>%
group_by(year) %>%
summarize(suicides_no = sum(suicides_no),
population = sum(population)) %>%
mutate(rate = 100000 * suicides_no/population)
ggplot() +
geom_line(data = who_subset, aes(year, rate))
}}
else if (gender()=="gender_specific"){
if (country()=="World"){
who_all <- who %>%
group_by(year) %>%
summarize(suicides_no = sum(suicides_no),
population = sum(population)) %>%
mutate(rate = 100000 * suicides_no/population)
ggplot() +
geom_line(data = who_all, aes(year, rate))
}
else {
#create a new subset of data that will be used??
who_subset<-subset(who, country==input$country)
who_sub_sex <- who_subset %>%
group_by(year, sex) %>%
summarize(suicides_no = sum(suicides_no),
population = sum(population)) %>%
mutate(rate = 100000 * suicides_no / population)
ggplot() +
geom_line(data = who_sub_sex, aes(year, rate, color = sex))}
}
}
)}
# Create a Shiny app object
shinyApp(ui = ui, server = server)
dput(head(who))
structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L, 1L),
.Label = c("Albania",
"Anguilla", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba",
"Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Barbados",
"Belarus", "Belgium", "Belize", "Bermuda", "Bolivia",
"Bosnia and Herzegovina",
"Brazil", "British Virgin Islands", "Brunei Darussalam", "Bulgaria",
"Cabo Verde", "Canada", "Cayman Islands", "Chile", "Colombia",
"Costa Rica", "Croatia", "Cuba", "Cyprus", "Czech Republic",
"Denmark", "Dominica", "Dominican Republic", "Ecuador", "Egypt",
"El Salvador", "Estonia", "Falkland Islands (Malvinas)", "Fiji",
"Finland", "France", "French Guiana", "Georgia", "Germany", "Greece",
"Grenada", "Guadeloupe", "Guatemala", "Guyana", "Haiti", "Honduras",
"Hong Kong SAR", "Hungary", "Iceland", "Iran (Islamic Rep of)",
"Iraq", "Ireland", "Israel", "Italy", "Jamaica", "Japan", "Jordan",
"Kazakhstan", "Kiribati", "Kuwait", "Kyrgyzstan", "Latvia", "Lithuania",
"Luxembourg", "Macau", "Malaysia", "Maldives", "Malta", "Martinique",
"Mauritius", "Mayotte", "Mexico", "Monaco", "Mongolia", "Montenegro",
"Montserrat", "Morocco", "Netherlands", "Netherlands Antilles",
"New Zealand", "Nicaragua", "Norway", "Occupied Palestinian Territory",
"Oman", "Panama", "Paraguay", "Peru", "Philippines", "Poland",
"Portugal", "Puerto Rico", "Qatar", "Republic of Korea",
"Republic of Moldova",
"Reunion", "Rodrigues", "Romania", "Russian Federation",
"Saint Kitts and Nevis",
"Saint Lucia", "Saint Pierre and Miquelon",
"Saint Vincent and Grenadines",
"San Marino", "Sao Tome and Principe", "Saudi Arabia", "Serbia",
"Seychelles", "Singapore", "Slovakia", "Slovenia", "South Africa",
"Spain", "Sri Lanka", "Suriname", "Sweden", "Switzerland",
"Syrian Arab Republic",
"Tajikistan", "TFYR Macedonia", "Thailand", "Trinidad and Tobago",
"Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands",
"Ukraine", "United Arab Emirates", "United Kingdom",
"United States of America",
"Uruguay", "Uzbekistan", "Venezuela (Bolivarian Republic of)",
"Virgin Islands (USA)", "Zimbabwe"), class = "factor"),
year = c(1985L, 1985L, 1985L, 1985L, 1985L, 1985L),
sex = structure(c(1L, 1L, 1L, 1L, 1L, 1L),.
Label = c("female", "male"), class = "factor"),
age = structure(1:6, .Label = c("15-24 years", "25-34 years",
"35-54 years", "5-14 years", "55-74 years", "75+ years"),
class = "factor"),
suicides_no = c(NA_integer_, NA_integer_, NA_integer_, NA_integer_,
NA_integer_, NA_integer_), population = c(277900L, 246800L,
267500L, 298300L, 138700L, 34200L)),
row.names = c(NA, 6L), class = "data.frame")
Is there any chance somebody knows a way out of this problem? Again I want the web app to output line graph when the user chooses x axis = year and gender = gender_neutral.
Try out with this server code.
The changes are already described in my comments. Since I dont have the who data.frame I could not test it.
server <- function(input, output) {
output$graph <- renderPlot({
if (input$x == "age") {
if (input$gender=="gender_neutral"){
if (input$country=="World"){
ggplot(data = who, aes(x = age)) + geom_bar(aes(weights = suicides_no), position="dodge")}
else {
#create a new subset of data that will be used??
who_subset <- subset(who, country == input$country)
ggplot(data=who_subset, aes(x=age)) + geom_bar(aes(weights=suicides_no))
}
} else if (input$gender=="gender_specific") {
if (input$country=="World"){
ggplot(data=who, aes(x=age)) + geom_bar(aes(weights=suicides_no, fill=sex), position="dodge")}
else {
#create a new subset of data that will be used??
who_subset <- subset(who, country==input$country)
ggplot(data = who_subset, aes(x=age)) + geom_bar(aes(weights=suicides_no, fill=sex), position="dodge")
}
}
} else if (input$x=="year"){
if (input$gender=="gender_neutral"){
if (input$country=="World"){
who_all <- who %>%
group_by(year) %>%
summarize(suicides_no = sum(suicides_no),
population = sum(population)) %>%
mutate(rate = 100000 * suicides_no/population)
ggplot() +
geom_line(data = who_all, aes(year, rate))
} else {
who_subset <- subset(who, country==input$country)
who_sub_sex <- who_subset %>%
group_by(year) %>%
summarize(suicides_no = sum(suicides_no),
population = sum(population)) %>%
mutate(rate = 100000 * suicides_no/population)
ggplot() +
geom_line(data = who_sub_sex, aes(year, rate))
}
} else if (input$gender=="gender_specific"){
if (input$country=="World"){
who_all <- who %>%
group_by(year) %>%
summarize(suicides_no = sum(suicides_no),
population = sum(population)) %>%
mutate(rate = 100000 * suicides_no/population)
ggplot() +
geom_line(data = who_all, aes(year, rate))
} else {
#create a new subset of data that will be used??
who_subset <- subset(who, country==input$country)
who_sub_sex <- who_subset %>%
group_by(year, sex) %>%
summarize(suicides_no = sum(suicides_no),
population = sum(population)) %>%
mutate(rate = 100000 * suicides_no / population)
ggplot() +
geom_line(data = who_sub_sex, aes(year, rate, color = sex))}
}
}
})
}

ggmap with value showing on the countries

I am looking for some help with the given sample data of countries on one column and count on another column. I am trying a build a geo maps using ggplot showing the count and name of the country in the respective places of the map when I hover above the country. Below is the sample data given. I tried with the ggmap with the lat and long position to identify the country but not able to show the count and name of the country on hovering.
structure(list(Countries = c("USA", "India", "Europe", "LATAM",
"Singapore", "Phillipines", "Australia", "EMEA", "Malaysia",
"Hongkong", "Philippines", "Thailand", "New Zealand"
), count = c(143002, 80316, 33513, 3736, 2180, 1905, 1816, 921,
707, 631, 207, 72, 49)), .Names = c("Countries", "count"), row.names = c(NA,
13L), class = "data.frame")
I tried the below code.
countries = geocode(Countryprofile$Countries)
Countryprofile = cbind(Countryprofile,countries)
mapWorld <- borders("world", colour="grey", fill="lightblue")
q<-ggplot(data = Countryprofile) + mapWorld + geom_point(aes(x=lon, y=lat) ,color="red", size=3)+
geom_text(data = Countryprofile,aes(x=lon,y=lat,label=Countries))
ggplotly(q)
You can change any attribute in the result from ggplotly. In this case you can set the text attribute of the 2nd trace (where you markers are defined).
plotly_map <- ggplotly(q)
plotly_map$x$data[[2]]$text <- paste(Countryprofile$Countries,
Countryprofile$count,
sep='<br />')
plotly_map
library(plotly)
library(ggmap)
Countryprofile <- structure(list(Countries = c("USA", "India", "Europe", "LATAM",
"Singapore", "Phillipines", "Australia", "EMEA", "Malaysia",
"Hongkong", "Philippines", "Thailand", "New Zealand"
), count = c(143002, 80316, 33513, 3736, 2180, 1905, 1816, 921,
707, 631, 207, 72, 49)), .Names = c("Countries", "count"), row.names = c(NA,
13L), class = "data.frame")
countries = geocode(Countryprofile$Countries)
Countryprofile = cbind(Countryprofile,countries)
mapWorld <- borders("world", colour="grey", fill="lightblue")
q<-ggplot(data = Countryprofile) + mapWorld + geom_point(aes(x=lon, y=lat) ,color="red", size=3)+
geom_text(data = Countryprofile,aes(x=lon,y=lat,label=Countries))
plotly_map <- ggplotly(q)
plotly_map$x$data[[2]]$text <- paste(Countryprofile$Countries, Countryprofile$count, sep='<br />')
plotly_map

Resources