white space in shiny - r

I am making an app in shiny, but I would like to know if it is possible to separate two inputs a bit. Something like what you see in the picture:
Expected space
Im not sure what I need to get a white space
The ui I'm using is the following:
datoscovid <- read_excel("/Users/jorge_hca/Desktop/Trabajo/datacovid.xlsx")
coordenadas <- read_excel("/Users/jorge_hca/Desktop/Trabajo/world_countrys.xlsx")
datoscov1 <- datoscovid |>
left_join(coordenadas, by = c("location" = "name"))
theme <- bs_theme(
bg = "#000000", fg = "#B8BCC2",
"input-border-color" = "#a6a6a6"
)
ui <- bootstrapPage(
absolutePanel(
top = 10, left = 50, style = "z-index:500; text-align: right;",
tags$h2("Los ingresos en México por deciles")
),
theme = theme,
useShinyalert(),
tags$style(type = "text/css", "html, body {width:100%;height:100%}"),
leafletOutput("map", width = "100%", height = "100%"),
absolutePanel(top = 10, right = 10,
fluidRow(dateInput("fecha", "Fecha a graficar:", width = 180,value = "2021-02-12"),
selectInput("var", "Escoge un país:", width = 180,
c("Antigua y Barbuda" = "Antigua and Barbuda",
"Argentina" = "Argentina",
"Bahamas" = "Bahamas",
"Barbados" = "Barbados",
"Belice" = "Belize",
"Bolivia" = "Bolivia",
"Brasil" = "Brazil",
"Canada" = "Canada",
"Chile" = "Chile",
"Colombia" = "Colombia",
"Costa Rica" = "Costa Rica",
"Cuba" = "Cuba",
"Dominica" = "Dominica",
"Republica Dominicana" = "Dominican Republic",
"Ecuador" = "Ecuador",
"El Salvador" = "El Salvador",
"Groenlandia" = "Greenland",
"Grenada" = "Grenada",
"Guatemala" = "Guatemala",
"Guyana" = "Guyana",
"Haiti" = "Haiti",
"Honduras" = "Honduras",
"Jamaica" = "Jamaica",
"Mexico" = "Mexico",
"Nicaragua" = "Nicaragua",
"Panama" = "Panama",
"Paraguay" = "Paraguay",
"Peru" = "Peru",
"Trinidad y Tobago" = "Trinidad and Tobago",
"Estados Unidos" = "United States",
"Uruguay" = "Uruguay",
"Venezuela" = "Venezuela"
), selected = "Mexico" )),
echarts4rOutput("graf", height = '350px', width = '550px'),
)
)
Any ideas or suggestions?

You can insert an empty div with a height between your two inputs:
selectInput(......),
div(style = "height:100px"),
echarts4rOutput(......)

Related

How to bring a chord diagram to a similar form?

I have a database.
I want to build a chord diagram similar to this one:
https://i.stack.imgur.com/59JcJ.png
My code:
vertices <- data.frame(name = unique(c(as.character(imports$Partner), as.character(imports$Reporter))) )
mygraph <- graph_from_data_frame( imports, vertices=vertices )
from <- match( imports$Reporter, vertices$name)
to <- match( imports$Partner, vertices$name)
ggraph(mygraph, layout = 'dendrogram', circular = TRUE)
geom_conn_bundle(data = get_con(from = from, to = to), alpha=0.2, colour="skyblue", tension = 0)
geom_node_point(aes(filter = leaf, x = x*1.05, y=y*1.05))
theme_void()
Result:
https://i.stack.imgur.com/uY2Yq.png
I searched for all kinds of settings for the chord diagram, but I didn’t find, how to make the links of the same size, and set the number of lines as an indicator of the value. Does anyone know how to create such a diagram?
data=structure(list(Reporter = c("USA", "USA", "USA", "USA", "India",
"Japan", "Japan", "USA", "Rep. of Korea", "USA", "Japan", "Japan",
"Japan", "Rep. of Korea", "USA", "USA", "USA", "China", "USA",
"USA", "Rep. of Korea", "USA", "Japan", "Japan", "Rep. of Korea",
"China", "China", "Rep. of Korea", "India", "China", "Rep. of Korea",
"USA", "Rep. of Korea", "Japan", "China", "Rep. of Korea", "India",
"China", "China", "India", "China", "China"), Partner = c("Saudi Arabia", "Canada", "Venezuela", "Mexico",
"Areas, nes", "Saudi Arabia", "United Arab Emirates", "Nigeria",
"Saudi Arabia", "Iraq", "Iran", "Qatar", "Kuwait", "United Arab Emirates",
"Angola", "Norway", "Colombia", "Oman", "United Kingdom", "Kuwait",
"Iran", "Gabon", "Indonesia", "Oman", "Kuwait", "Angola", "Iran",
"Oman", "Saudi Arabia", "Saudi Arabia", "Qatar", "Ecuador", "Indonesia",
"China", "Indonesia", "Australia", "Nigeria", "Yemen", "Fmr Sudan",
"Kuwait", "Iraq", "Viet Nam", "Iraq", "Australia", "Angola",
"United Arab Emirates", "Argentina", "Iran", "Trinidad and Tobago",
"Congo", "Yemen", "Iraq", "Viet Nam", "Australia", "Malaysia",
"Mexico", "Indonesia", "China", "Congo", "Ecuador", "Malaysia",
"Qatar", "Brunei Darussalam", "Norway"), Qty = c(69785202126, 68349221243, 68326932683,
64923669168, 57159000064, 53691639675, 52396394737, 46817696134,
38307387772, 31471382247, 25554794183, 19184268129, 18481591406,
16695296617, 16497467586, 16029110463, 15953011573, 15660839936,
14459452736, 13796910873, 11134838478, 10393629031, 10258716565,
9751327665, 9417368771, 8636634112, 7000465408, 6586187350, 5769723904,
5730211328, 5702528697, 5553458497, 5290777764, 5113191253, 4575188480,
4361612670, 3888963072, 3612423424, 3313590784, 3223781888, 3183182080,
3158472192, 3151280715, 3081015515, 3067260000, 2921931008, 2850134892,
2607684096, 2587749446, 2547349198, 2485083122, 2443798762, 2365431992,
2342513214, 2308853961, 2130664704, 1942125162, 1828376381, 1814260579,
1785874000, 1609282280, 1598901888, 1534923974, 1477843712, 1476737920,
1454356736, 1355873401, 1293729024, 1285355978, 1278701346, 1259876360,
1252518912, 1248772992, 1223383808, 1163368000, 1144188000, 1108399232,
1062041363, 1041526592, 977722731, 897418483, 877541040, 845556546,
801940467, 744316800, 739848000, 724177472, 694896000, 685405539,
672387008, 554965585, 540327751, 508204324, 4.87e+08, 457252032,
433428000, 430473920, 426744352, 408635880, 392727578, 390598528,
390189912, 389451923, 384376548, 350920922, 327039700, 285413702,
285143680, 275486240, 274015471, 264478000, 260122000, 238997756,
227806048, 204376795, 192144011, 150791409, 140634221, 135842986,
130777039, 129973032, 125115000, 124681401, 123443000, 120061792,
110795499, 106762492, 105548008, 84693986, 70275359, 57248174,
47944463, 40236018, 30783728, 18364000, 13419253, 12551365, 9631763,
5994199, 374000, 350000, 339115, 86420, 24000, 180)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -145L))

How to hide, or at least customize colorbar in plotly scattergeo in R

I want to create a scattergeo plot with markers for capitals. These markers are sized and colored regarding database values.
If I use the standard colors, everything goes well : the map is shown properly with good size, different colors, and no legend (I add the information country:value in a hover text on the markers).
However if I use a custom palette using colors feature into my scattergeo plot the colorbar is always displayed. Showlegend=F and Showscale=F doesn't help. Since I remove colors the colorbar disapeared.
Moreover, if I try to customize it (eg change the title or the format of the tickslabels) it doesn't work.
In other words no option I have tried on this colorbar works !
This is my data :
structure(list(ISO3 = c("ARG", "AUS", "AUT", "BEL", "BRA", "CAN",
"CHE", "CHL", "CHN", "COK", "DEU", "DNK", "ESP", "FIN", "FJI",
"FRA", "GBR", "HKG", "IDN", "IND", "ITA", "JPN", "KOR", "LUX",
"MEX", "MYS", "NCL", "NLD", "NOR", "NZL", "PHL", "PRT", "RUS",
"SGP", "SWE", "THA", "TON", "USA", "WSM"), Total = c(1073L, 8204L,
818L, 1502L, 1871L, 7958L, 3524L, 2456L, 3345L, 456L, 5010L,
569L, 2775L, 184L, 75L, 60382L, 4424L, 415L, 146L, 405L, 8369L,
8176L, 1034L, 235L, 961L, 137L, 6522L, 667L, 309L, 7960L, 238L,
316L, 486L, 404L, 480L, 200L, 41L, 85225L, 46L), Size = c(16,
30, 14, 18, 19, 30, 24, 21, 23, 12, 26, 13, 22, 8, 5, 50, 25,
11, 7, 11, 30, 30, 16, 9, 15, 7, 28, 13, 10, 30, 9, 10, 12, 11,
12, 8, 3, 54, 4), Color = c(3, 4, 3, 3, 3, 4, 4, 3, 4, 3, 4,
3, 3, 2, 2, 5, 4, 3, 2, 3, 4, 4, 3, 2, 3, 2, 4, 3, 2, 4, 2, 2,
3, 3, 3, 2, 2, 5, 2), ISO2 = c("AR", "AU", "AT", "BE", "BR",
"CA", "CH", "CL", "CN", "CK", "DE", "DK", "ES", "FI", "FJ", "FR",
"GB", "HK", "ID", "IN", "IT", "JP", "KR", "LU", "MX", "MY", "NC",
"NL", "NO", "NZ", "PH", "PT", "RU", "SG", "SE", "TH", "TO", "US",
"WS"), LABELFR = c("Argentine", "Australie", "Autriche", "Belgique",
"Brésil", "Canada", "Suisse", "Chili", "Chine", "Iles Cook",
"Allemagne", "Danemark", "Espagne", "Finlande", "Fidji", "France",
"Royaume-Uni", "Hong-kong, Chine", "Indonésie", "Inde", "Italie",
"Japon", "Corée, République de", "Luxembourg", "Mexique", "Malaisie",
"Nouvelle-Calédonie", "Pays-Bas", "Norvège", "Nouvelle-Zélande",
"Philippines", "Portugal", "Russie, Fédération de", "Singapour",
"Suède", "Thaïlande", "Tonga", "Etats-Unis", "Samoa"), LABELEN = c("Argentina",
"Australia", "Austria", "Belgium", "Brazil", "Canada", "Switzerland",
"Chile", "China", "Cook Islands", "Germany", "Denmark", "Spain",
"Finland", "Fiji", "France", "United Kingdom", "Hong Kong", "Indonesia",
"India", "Italy", "Japan", "South Korea", "Luxembourg", "Mexico",
"Malaysia", "New Caledonia", "Netherlands", "Norway", "New Zealand",
"Philippines", "Portugal", "Russia", "Singapore", "Sweden", "Thailand",
"Tonga", "United States", "Samoa"), CAPITAL = c("Buenos Aires",
"Canberra", "Vienna", "Brussels", "Brasilia", "Ottawa", "Bern",
"Santiago", "Beijing", "Avarua", "Berlin", "Copenhagen", "Madrid",
"Helsinki", "Suva", "Paris", "London", "N/A", "Jakarta", "New Delhi",
"Rome", "Tokyo", "Seoul", "Luxembourg", "Mexico City", "Kuala Lumpur",
"Noumea", "Amsterdam", "Oslo", "Wellington", "Manila", "Lisbon",
"Moscow", "Singapore", "Stockholm", "Bangkok", "Nuku'alofa",
"Washington", "Apia"), LATITUDE = c("-34.583333333333336", "-35.266666666666666",
"48.2", "50.833333333333336", "-15.783333333333333", "45.416666666666664",
"46.916666666666664", "-33.45", "39.916666666666664", "-21.2",
"52.516666666666666", "55.666666666666664", "40.4", "60.166666666666664",
"-18.133333333333333", "48.86666666666667", "51.5", "0", "-6.166666666666667",
"28.6", "41.9", "35.68333333333333", "37.55", "49.6", "19.433333333333334",
"3.1666666666666665", "-22.266666666666666", "52.35", "59.916666666666664",
"-41.3", "14.6", "38.71666666666667", "55.75", "1.2833333333333332",
"59.333333333333336", "13.75", "-21.133333333333333", "38.883333",
"-13.816666666666666"), LONGITUDE = c("-58.666667", "149.133333",
"16.366667", "4.333333", "-47.916667", "-75.700000", "7.466667",
"-70.666667", "116.383333", "-159.766667", "13.400000", "12.583333",
"-3.683333", "24.933333", "178.416667", "2.333333", "-0.083333",
"0.000000", "106.816667", "77.200000", "12.483333", "139.750000",
"126.983333", "6.116667", "-99.133333", "101.700000", "166.450000",
"4.916667", "10.750000", "174.783333", "120.966667", "-9.133333",
"37.600000", "103.850000", "18.050000", "100.516667", "-175.200000",
"-77.000000", "-171.766667"), CONTINENT = c("South America",
"Australia", "Europe", "Europe", "South America", "Central America",
"Europe", "South America", "Asia", "Australia", "Europe", "Europe",
"Europe", "Europe", "Australia", "Europe", "Europe", "Asia",
"Asia", "Asia", "Europe", "Asia", "Asia", "Europe", "Central America",
"Asia", "Australia", "Europe", "Europe", "Australia", "Asia",
"Europe", "Europe", "Asia", "Europe", "Asia", "Australia", "Central America",
"Australia")), class = c("data.table", "data.frame"), row.names = c(NA,
-39L), .internal.selfref = <pointer: 0x000001ffb6417970>, sorted = "ISO3")
This is my code :
fig <- plot_ly(
type = 'scattergeo',
showlegend=F,
mode='markers',
data=TOUR,
y=~LATITUDE,
x=~LONGITUDE,
text=sprintf("%s : %s",TOUR$LABELFR,TOUR$Total),
hovertemplate = "%{text}<extra></extra>",
colors=c(ispfPalette[c(9,4,2)]),
color=~Color,
marker=list(
showscale=F,
size=~Size,
reversescale=F
)
)
And this is the output I have :
Best solution would be to hide completely the colorbar, but I would also be curious how to customize it by changing the title and formatting the values (per example in case of % or if I want to change the decimal separator).
Thanks for your help !
Update on request:
You could modify the colorbar in the colors argument, for example like this:
fig <- plot_ly(
type = 'scattergeo',
showlegend=F,
mode='markers',
data=TOUR,
y=~LATITUDE,
x=~LONGITUDE,
text=sprintf("%s : %s",TOUR$LABELFR,TOUR$Total),
hovertemplate = "%{text}<extra></extra>",
colors="YlOrRd",
#colors = c("#1B98E0","black"),
color=~Color,
marker=list(
showscale=F,
size=~Size,
reversescale=F
)
)
fig
colors="YlOrRd"
colors = c("#1B98E0","black")
ORIGINAL ANSWER:
Just add: %>% hide_colorbar at the end of your code:
fig <- plot_ly(
type = 'scattergeo',
showlegend=F,
mode='markers',
data=TOUR,
y=~LATITUDE,
x=~LONGITUDE,
text=sprintf("%s : %s",TOUR$LABELFR,TOUR$Total),
hovertemplate = "%{text}<extra></extra>",
colors=c(ispfPalette[c(9,4,2)]),
color=~Color,
marker=list(
showscale=F,
size=~Size,
reversescale=F
)
) %>% hide_colorbar()

How to assign colors and line types of multiple vertical lines in each plot in the sapply function?

I generated multiple plots with vertical lines in each plot using the following codes:
I was wondering if there's any way to change colours and line types of each vertical lines on this codes:
library(gridExtra)
library(grid)
library(lattice)
library(ggplot2)
vertical.lines <- c(1990,1991)
df1 %>%
filter(isocode == "KOR") %>%
select(year,rgdpe, rgdpo, avh, emp, hc) %>%
tidyr::gather(predictor, value, -year)%>%
ggplot() +
geom_line(aes(year, value))+
facet_wrap(~predictor, scales = "free")+
labs(x = NULL, y = NULL, top = "Title of the Chart",
bottom = textGrob(
"Data source: World Bank",
gp = gpar(fontface = 3, fontsize = 9),
hjust = 1,x = 1))+ sapply(vertical.lines, function(xint) geom_vline(aes(xintercept = xint)))
I want to put something like
lty = c(3,1), color = c("blue","red"), lwd=c(.5,.5))
But I don't know how to apply to my code.
My data looks like to have the structure like the following
Maybe if you need, I can add more variables.
structure(list(country = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("Aruba",
"Angola", "Anguilla", "Albania", "United Arab Emirates", "Argentina",
"Armenia", "Antigua and Barbuda", "Australia", "Austria", "Azerbaijan",
"Burundi", "Belgium", "Benin", "Burkina Faso", "Bangladesh",
"Bulgaria", "Bahrain", "Bahamas", "Bosnia and Herzegovina", "Belarus",
"Belize", "Bermuda", "Bolivia (Plurinational State of)", "Brazil",
"Barbados", "Brunei Darussalam", "Bhutan", "Botswana", "Central African Republic",
"Canada", "Switzerland", "Chile", "China", "Cote d'Ivoire", "Cameroon",
"Congo, Democratic Republic", "Congo", "Colombia", "Comoros",
"Cabo Verde", "Costa Rica", "Curacao", "Cayman Islands", "Cyprus",
"Czech Republic", "Germany", "Djibouti", "Dominica", "Denmark",
"Dominican Republic", "Algeria", "Ecuador", "Egypt", "Spain",
"Estonia", "Ethiopia", "Finland", "Fiji", "France", "Gabon",
"United Kingdom", "Georgia", "Ghana", "Guinea", "Gambia", "Guinea-Bissau",
"Equatorial Guinea", "Greece", "Grenada", "Guatemala", "Guyana",
"China, Hong Kong SAR", "Honduras", "Croatia", "Haiti", "Hungary",
"Indonesia", "India", "Ireland", "Iran (Islamic Republic of)",
"Iraq", "Iceland", "Israel", "Italy", "Jamaica", "Jordan", "Japan",
"Kazakhstan", "Kenya", "Kyrgyzstan", "Cambodia", "Saint Kitts and Nevis",
"Republic of Korea", "Kuwait", "Lao People's DR", "Lebanon",
"Liberia", "Saint Lucia", "Sri Lanka", "Lesotho", "Lithuania",
"Luxembourg", "Latvia", "China, Macao SAR", "Morocco", "Republic of Moldova",
"Madagascar", "Maldives", "Mexico", "North Macedonia", "Mali",
"Malta", "Myanmar", "Montenegro", "Mongolia", "Mozambique", "Mauritania",
"Montserrat", "Mauritius", "Malawi", "Malaysia", "Namibia", "Niger",
"Nigeria", "Nicaragua", "Netherlands", "Norway", "Nepal", "New Zealand",
"Oman", "Pakistan", "Panama", "Peru", "Philippines", "Poland",
"Portugal", "Paraguay", "State of Palestine", "Qatar", "Romania",
"Russian Federation", "Rwanda", "Saudi Arabia", "Sudan", "Senegal",
"Singapore", "Sierra Leone", "El Salvador", "Serbia", "Sao Tome and Principe",
"Suriname", "Slovakia", "Slovenia", "Sweden", "Eswatini", "Sint Maarten (Dutch part)",
"Seychelles", "Syrian Arab Republic", "Turks and Caicos Islands",
"Chad", "Togo", "Thailand", "Tajikistan", "Turkmenistan", "Trinidad and Tobago",
"Tunisia", "Turkey", "Taiwan", "U.R. of Tanzania: Mainland",
"Uganda", "Ukraine", "Uruguay", "United States of America", "Uzbekistan",
"St. Vincent & Grenadines", "Venezuela (Bolivarian Republic of)",
"British Virgin Islands", "Viet Nam", "Yemen", "South Africa",
"Zambia", "Zimbabwe"), class = "factor"), isocode = c("ABW",
"ABW", "ABW", "ABW", "ABW"), year = 1990:1994, currency = structure(c(4L,
4L, 4L, 4L, 4L), .Label = c("Algerian Dinar", "Argentine Peso",
"Armenian Dram", "Aruban Guilder", "Australian Dollar", "Azerbaijanian Manat",
"Bahamian Dollar", "Bahraini Dinar", "Baht", "Balboa", "Barbados Dollar",
"Belarussian Ruble", "Belize Dollar", "Bermudian Dollar", "Bolivar Fuerte",
"Boliviano", "Brazilian Real", "Brunei Dollar", "Bulgarian Lev",
"Burundi Franc", "CFA Franc BCEAO", "CFA Franc BEAC", "Cabo Verde Escudo",
"Canadian Dollar", "Cayman Islands Dollar", "Cedi", "Chilean Peso",
"Colombian Peso", "Comoro Franc", "Convertible Marks", "Cordoba Oro",
"Costa Rican Colon", "Croatian Kuna", "Czech Koruna", "Dalasi",
"Danish Krone", "Denar", "Djibouti Franc", "Dobra", "Dominican Peso",
"Dong", "East Caribbean Dollar", "Egyptian Pound", "Ethiopian Birr",
"Euro", "Fiji Dollar", "Forint", "Franc Congolais", "Gourde",
"Guarani", "Guinea Franc", "Guyana Dollar", "Hong Kong Dollar",
"Hryvnia", "Iceland Krona", "Indian Rupee", "Iranian Rial", "Iraqi Dinar",
"Jamaican Dollar", "Jordanian Dinar", "Kenyan Shilling", "Kip",
"Kuwaiti Dinar", "Kwacha", "Kwanza", "Kyat", "Lari", "Lebanese Pound",
"Lek", "Lempira", "Leone", "Lilangeni", "Loti", "Malagasy Ariary",
"Malaysian Ringgit", "Manat", "Mauritius Rupee", "Metical", "Mexican Peso",
"Moldovan Leu", "Moroccan Dirham", "Naira", "Namibian Dollar",
"Nepalese Rupee", "Netherlands Antillian Guilder", "New Israeli Sheqel",
"New Leu", "New Taiwan Dollar", "New Turkish Lira", "New Zealand Dollar",
"Ngultrum", "Norwegian Krone", "Nuevo Sol", "Ouguiya", "Pakistan Rupee",
"Pataca", "Peso Uruguayo", "Philippine Peso", "Pound Sterling",
"Pula", "Qatari Rial", "Quetzal", "Rand", "Rial Omani", "Riel",
"Rufiyaa", "Rupiah", "Russian Ruble", "Rwanda Franc", "Saudi Riyal",
"Serbian Dinar", "Seychelles Rupee", "Singapore Dollar", "Som",
"Somoni", "Sri Lanka Rupee", "Sudanese Pound", "Surinam Dollar",
"Swedish Krona", "Swiss Franc", "Syrian Pound", "Taka", "Tanzanian Shilling",
"Tenge", "Trinidad and Tobago Dollar", "Tugrik", "Tunisian Dinar",
"UAE Dirham", "US Dollar", "Uganda Shilling", "Uzbekistan Sum",
"Won", "Yemeni Rial", "Yen", "Yuan Renminbi", "Zloty"), class = "factor"),
rgdpe = c(2574.41870117188, 2803.42724609375, 2943.32641601562,
3130.13989257812, 3535.80346679688), rgdpo = c(3043.74633789062,
3204.01831054688, 3399.08251953125, 3711.45483398438, 4192.33935546875
), pop = c(0.062149, 0.064622, 0.068235, 0.072504, 0.0767
), emp = c(NA, 0.0292000006884336, 0.030903272330761, 0.0329118072986603,
0.0348959788680077), avh = c(NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_), hc = c(NA_real_, NA_real_, NA_real_,
NA_real_, NA_real_)), row.names = c("ABW-1990", "ABW-1991",
"ABW-1992", "ABW-1993", "ABW-1994"), class = "data.frame")
One option to achieve your desired result would be to make use of purrr::pmap or mapply which both allow you to loop over multiple vectors or lists simultaneously.
Additionally, if you want to add title and/or caption you could do so via the title and caption arguments of labs()and set the style via theme options.
library(ggplot2)
library(tidyr)
library(dplyr)
library(purrr)
df1 %>%
select(year, rgdpe, rgdpo, avh, emp, hc) %>%
tidyr::gather(predictor, value, -year) %>%
ggplot() +
geom_line(aes(year, value)) +
facet_wrap(~predictor, scales = "free") +
labs(x = NULL, y = NULL, title = "Title of the Chart", caption = "Data source: World Bank") +
theme(plot.caption = element_text(face = 3, size = 9, hjust = 1)) +
purrr::pmap(
data.frame(
xint = c(1990, 1991),
lty = c(3, 1),
color = c("blue", "red")
),
function(xint, lty, color, lwd) geom_vline(xintercept = xint, color = color, linetype = lty, size = .5)
)

Label plot based on condition [duplicate]

This question already has an answer here:
Conditional labeling in ggplot2 using geom_text and subsetting
(1 answer)
Closed 1 year ago.
I have a dot plot with data from dataframe df_roles$result and would like to assign labels only to certain dots specified by their specific name in df_roles$name.
My expected output is to have e.g. China labelled.
I have tried both these arguments but they won't work:
ifelse(df_roles$name = "China",
text(df_roles[[3]], df_roles[[2]], labels = df_roles[[1]], pos = 2, cex=0.3), " ")
geom_text(data = filter(df_roles$result, df_roles$name=="China"),aes(label=df_roles$name))
Reproducible example:
df_roles <- structure(list(name = structure(1:6, .Label = c("Afghanistan",
"Albania", "Algeria", "Angola", "Argentina", "Armenia", "Australia",
"Austria", "Azerbaijan", "Bahrain", "Bangladesh", "Barbados",
"Belarus", "Belgium", "Belize", "Benin", "Bolivia", "Bosnia and Herzegovina",
"Botswana", "Brazil", "Bulgaria", "Burkina Faso", "Burundi",
"Cameroon", "Canada", "Chile", "China", "Colombia", "Congo",
"Costa Rica", "Croatia", "Cuba", "Cyprus", "Democratic Republic of the Congo",
"Denmark", "Dominican Republic", "Ecuador", "Egypt", "El Salvador",
"Eritrea", "Estonia", "Ethiopia", "Finland", "France", "Gabon",
"Gambia", "Georgia", "Germany", "Ghana", "Greece", "Grenada",
"Guatemala", "Guinea", "Guyana", "Haiti", "Honduras", "Hungary",
"India", "Indonesia", "Iran ", "Iraq", "Ireland", "Israel", "Italy",
"Jamaica", "Japan", "Jordan", "Kazakhstan", "Kenya", "Kuwait",
"Kyrgyzstan", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya",
"Lithuania", "Luxembourg", "Malawi", "Malaysia", "Mali", "Malta",
"Mauritania", "Mexico", "Mongolia", "Montenegro", "Morocco",
"Mozambique", "Namibia", "Nepal", "Netherlands", "New Zealand",
"Nicaragua", "Nigeria", "Norway", "Oman", "Pakistan", "Palestine",
"Panama", "Paraguay", "Peru", "Philippines", "Poland", "Portugal",
"Qatar", "Republic of Korea", "Republic of Moldova", "Romania",
"Russia", "Rwanda", "Saint Lucia", "Saint Vincent and the Grenadines",
"Saudi Arabia", "Senegal", "Serbia", "Singapore", "Slovakia",
"Slovenia", "Somalia", "South Africa", "Spain", "Sri Lanka",
"Sudan", "Suriname", "Sweden", "Switzerland", "Syria", "Taiwan",
"Tajikistan", "Thailand", "Togo", "Trinidad and Tobago", "Tunisia",
"Turkey", "Turkmenistan", "Uganda", "UK", "Ukraine", "United Arab Emirates",
"United Republic of Tanzania", "United States of America", "Uruguay",
"Uzbekistan", "Venezuela", "Viet Nam", "Yemen", "Zambia", "Zimbabwe"
), class = "factor"), result = c(0.0900102874778869, -0.0934265332577318,
-0.177974826946747, -0.590024694573266, 1.20884852383168, -0.183452483887309
)), row.names = c(NA, 6L), class = "data.frame")
Since the data shared does not have 'China' in it I am using 'Afghanistan' as an example. Also using row number as x-axis.
library(dplyr)
library(ggplot2)
df_roles %>%
mutate(name = as.character(name),
label = replace(name, name != 'Afghanistan', ''),
row = row_number()) %>%
ggplot(aes(row, result, label = label)) +
geom_point() + geom_text(vjust = -0.5)

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))}
}
}
})
}

Resources