ggplot multiple densities with common density - ggplot2

I would like to plot something that is "between" a histogram and a density plot. Here is an example:
library(ggplot2)
set.seed(1)
f1 <- rep(1, 100)
v1 <- rnorm(100)
df1 <- data.frame(f1, v1)
f1 <- rep(2, 10)
v1 <- (rnorm(10)+1*2)
df2 <- data.frame(f1, v1)
df <- rbind(df1, df2)
df$f1 <- as.factor(df$f1)
ggplot(df, aes(x = v1, colour = f1)) +
geom_density(position="identity", alpha = 0.6, fill = NA, size = 1)
You will see that the area under each curve is 1.0, which is OK for a density. BUT notice that the second distribution is made up of just 10 observations rather than the 100 of the first. What I would like is that the area under curve 2 reflects this, e.g. is a tenth of that of curve 1. Thanks.

There is a computed variable for stat_density that you can use, called count.
ggplot(df, aes(x = v1, colour = f1)) +
geom_density(position="identity", alpha = 0.6, fill = NA, size = 1,
aes(y = after_stat(count)))
Note for ggplot2 <3.3.0 use stat(count) instead of after_stat(count).
You can find these tricks in the documentation of ?geom_density() under the section "Computed Variables".

Related

Plotly does not properly show axis numbers with math_format

The code below indicates that, while using math_format command in ggplot 'labels', the plot displays well if ggplot is used, but it fails if it is displayed through plotly. I need to use plotly in my code. Does somebody have some suggestion?
library(tidyverse)
library(scales)
library(plotly)
p <- mtcars %>% ggplot(aes(x=mpg, y=disp))+
geom_point() +
scale_x_continuous(trans = log_trans(),
breaks = trans_breaks("log", function(x) exp(x), n.breaks = 5),
labels = trans_format("log", math_format(e^.x, format = function(x) number(x, accuracy = 0.01, decimal.mark = ','))))
p
ggplotly(p)

Surface plotting with ggplot2

Is it possible to plot with ggplot2 3D surface which is presented as (x, y, z)-vector with labeled countour lines?
Desired result is presented below
Surface map with countour lines
This is exactly what the geomtextpath package was built for.
Example copied from ?geomtextpath::geom_textcontour
library(geomtextpath)
#> Loading required package: ggplot2
df <- expand.grid(x = seq(nrow(volcano)), y = seq(ncol(volcano)))
df$z <- as.vector(volcano)
ggplot(df, aes(x, y, z = z)) +
geom_contour_filled(bins = 6, alpha = 0.6) +
geom_textcontour(bins = 6, size = 2.5, padding = unit(0.05, "in")) +
scale_fill_manual(values = terrain.colors(11)) +
theme_classic() +
theme(legend.position = "none")
Created on 2023-01-26 with reprex v2.0.2

plotting 'rworldmap' shapefile in ggplot2 across pacific ocean

I'm having issues making a plot in ggplot using some raster data I've gathered. I'll simulate the raster data as a dataframe here:
# Set up coordinates #
lon <- seq(120, 290, 1)
lat <- seq(-30, 30, 1)
r1 <- data.frame(
"lon" = rep(lon, length(lat)),
"lat" = rep(lat, each = length(lon))
)
# Add variable #
set.seed(2022)
r1$var <- rnorm(n = nrow(r1), 0, 1)
# Plot raster #
library(ggplot2)
p1 <- ggplot(r1, aes(x = lon, y = lat, fill = var))+
geom_raster()
p1
The issue I'm having is when I try to add a shapefile (specifically from rworldmap) to this plot. Because the data is projected in longitudes between -180 and 180 (instead of 0 to 360), it's unable to plot anything east of 180 East.
library(rworldmap)
library(sf)
# Download Shapefile #
world.shp <- getMap(resolution = 'low')
world.shp <- st_as_sf(world.shp)
# Plot shapefile on top of raster data #
p2 <- ggplot()+
geom_raster(data = r1, aes(x = lon, y = lat, fill = var))+
geom_sf(data = world.shp)+
coord_sf(xlim = c(120, 290), ylim = c(-30, 30), expand = TRUE)
p2
Notice how only Australia plots, when we should also be getting South America, Latin America, and North America.
I've tried many different strategies to reproject the rworldmap shapefile (world.shp), from defining a crs in st_as_sf() to specifying a crs in the coord_sf() argument. However, I've had no no success. The solution seems very simple, but I can't seem to find it. Any help with this would be greatly appreciated.
Cheers,

ggplot2 geom_text position in pie chart

I am plotting pie charts with ggplot2 and succeeded in having the percentage-labels centered in each slice
library(dplyr)
library(ggplot2)
library(ggpubr)
library("readxl")
df <- read_excel("Radiocomp.xlsx")
df$Pattern <- factor(cc$Pattern)
str(cc)
GGO <- ggplot(data=df, aes(x = "", y = GGO, fill = Pattern)) +
geom_bar(stat="identity", color = "white") +
geom_text(aes(label = paste0(GGO, "%")), position = position_stack(vjust = 0.5)) +
coord_polar("y") +
theme_void()
GGO
Pie chart
I try to place the percent-label outside the pie for better readability
Any recommendation?
Thank you
This can be achieved by setting the x aesthetic inside geom_text, e.g. x = 1.6 will put the label just outside of the pie.
library(ggplot2)
library(dplyr)
# example data
mpg1 <- mpg %>%
count(class) %>%
mutate(pct = n / sum(n))
ggplot(mpg1, aes(x = "", y = pct, fill = class)) +
geom_bar(stat = "identity", color = "white") +
geom_text(aes(x = 1.6, label = scales::percent(pct, accuracy = .1)), position = position_stack(vjust = .5)) +
coord_polar("y") +
theme_void()
Created on 2020-06-03 by the reprex package (v0.3.0)

How to adjust plot areas in ggplot?

I am trying to use grid.arrange to display multiple graphs on the same page generated by ggplot.Each subplot with difference x and y scale. Two subplot share the legend. My perpose is that to display the plot areas same size. Are there parameter to adjust plot area ( except legend area)? The facet is inadequate to arrange it.
df <- data.frame(class=paste0('a',1:20),
x1=runif(20),
x2=runif(20),
y1=runif(20),
y2=runif(20))
p1 <- ggplot(df,aes(x=x1,y=y1))+
geom_point(aes(color=class),size=2,show.legend=TRUE)+
stat_smooth(method='lm',color='black')+
theme_bw()
p2 <- ggplot(df,aes(x=x2,y=y2))+
geom_point(aes(color=class),size=2,show.legend=FALSE)+
stat_smooth(method='lm',color='black')+
theme_bw()
grid.arrange(p1,p2,nrow=2)
Using patchwork package
# install.packages("devtools", dependencies = TRUE)
# devtools::install_github("thomasp85/patchwork")
library(patchwork)
p1 / p2 + plot_annotation(title = "Plot title",
subtitle = "Plot subtitle",
tag_levels = 'A',
tag_suffix = ')')
Created on 2018-11-20 by the reprex package (v0.2.1.9000)