ggplot: edit shape of points based on second column - r

My goal is to plot a map with dwelling locations as points, where points are divided into two colours, based on a categorical variable, name category. Of those dwellings, a few dwellings need to have a different shape, e.g., a star. The column that describes this is called star in the example below. My dataframe looks like this:
x
y
category
star
123
456
1
0
143
556
0
0
124
556
1
1
233
256
1
0
ggplot(data = df, aes(x = x, y = y, color=category)) +
geom_point()
The code above gives me what I need, except for the 'stars'. How can distinguish this second column?

Have assumed you want the points with star with a value of 1 to be a star shape.
library(ggplot2)
ggplot(data = df1, aes(x = x, y = y, color=factor(category), shape = factor(star))) +
geom_point(size = 8) +
scale_shape_manual(breaks = c(0, 1),
values = c(1, 11))+
labs(color = "Category",
shape = "Star")
data
df1 <- structure(list(x = c(123L, 143L, 124L, 233L),
y = c(456L, 556L, 556L, 256L),
category = c(1L, 0L, 1L, 1L),
star = c(0L, 0L, 1L, 0L)),
class = "data.frame", row.names = c(NA, -4L))
Created on 2022-10-13 with reprex v2.0.2

Related

Plot data from data frame list

I have a list of data frames,
>head(df.list.xyg[["archae.list"]])
motif obs pred prop stat pval stdres
AAB 1189 760.1757 0.05556028 11811.94 0 16.00425
CDD 1058 249.7147 0.01825133 11811.94 0 51.62291
DDE 771 415.1314 0.03034143 11811.94 0 17.73730
FBB 544 226.3529 0.01654385 11811.94 0 21.28994
>head(df.list.xyg[["eukaryote.list"]])
motif obs pred prop stat pval stdres
ABG 82015 48922.33 0.08773749 321891.7 0 156.64562
GBC 51601 64768.42 0.11615591 321891.7 0 -55.03402
AGG 41922 30136.56 0.05404701 321891.7 0 69.80141
CGG 25545 14757.24 0.02646569 321891.7 0 90.00215
BTT 15795 12433.58 0.02229843 321891.7 0 30.48747
I would like to
barplot motif versus stdres such that the plots are displayed in single column but two rows, and
label each plot corresponding to part of the file name "archae", eukaryote and so on.
After searching around, the following code snippet does the job but only partly. It only plots the last dataset. I assume it is "overwriting" the earlier dataset. How do I fix this? Can this be achieved by face_wrap or facet_grid?
myplots<-lapply(df.list.xyg,
function(x)
p<-ggplot(x,aes(x=motif,y=stdres)) +
geom_bar(stat="identity",width=0.5, color="blue", fill="gray")
)
print (myplots)
If you just want the plots to appear together in a single plotting window, you can use facets. You can bind the rows of your data frames together with dplyr::bind_rows, which will create an id column to label which data frame each row belongs to. We facet by this ID variable.
library(ggplot2)
ggplot(dplyr::bind_rows(df.list.xyg, .id = "Kingdom"), aes(motif, stdres)) +
geom_col(width = 0.5, fill = "deepskyblue4") +
geom_hline(yintercept = 0, color = "gray75") +
facet_grid(.~Kingdom) +
theme_bw(base_size = 16)
If you have lots of different data frames in your list, facet_grid may be better than facet_wrap.
Depending on how you wish to present the data, you may prefer to save individual plots to files using ggsave inside your lapply
Reproducible data taken from question
df.list.xyg <- list(archae = structure(list(motif = c("AAB",
"CDD", "DDE", "FBB"), obs = c(1189L, 1058L, 771L, 544L),
pred = c(760.1757, 249.7147,
415.1314, 226.3529), prop = c(0.05556028, 0.01825133, 0.03034143,
0.01654385), stat = c(11811.94, 11811.94, 11811.94, 11811.94),
pval = c(0L, 0L, 0L, 0L), stdres = c(16.00425, 51.62291,
17.7373, 21.28994)), class = "data.frame", row.names = c(NA,
-4L)), eukaryote.list = structure(list(motif = c("ABG", "GBC",
"AGG", "CGG", "BTT"), obs = c(82015L, 51601L, 41922L, 25545L,
15795L), pred = c(48922.33, 64768.42, 30136.56, 14757.24, 12433.58
), prop = c(0.08773749, 0.11615591, 0.05404701, 0.02646569, 0.02229843
), stat = c(321891.7, 321891.7, 321891.7, 321891.7, 321891.7),
pval = c(0L, 0L, 0L, 0L, 0L), stdres = c(156.64562, -55.03402,
69.80141, 90.00215, 30.48747)), class = "data.frame", row.names = c(NA,
-5L)))
Created on 2022-05-23 by the reprex package (v2.0.1)
#allancameron: Elegant solution! Thanks. The key then is to row-bind so that the data can be facet-wrapped according to kingdom. I modified the code as below
plot in a single column-two rows
scale the y-axis according to the range of data
turn the y-axis labels 90 degrees for better readability.
library(ggplot2)
ggplot(dplyr::bind_rows(df.list.xyg, .id = "Kingdom"), aes(motif, stdres)) +
geom_col(width = 0.5, fill = "deepskyblue4") +
geom_hline(yintercept = 0, color = "gray75") +
facet_grid(Kingdom ~ ., scales = "free") +
theme_bw(base_size = 16)

plotting means in a horizontal bar with a vertical line

ID
score1
score 2
score 3
score 4
1
200
300
400
-200
2
250
-310
-470
-200
3
210
400
480
-200
4
220
-10
-400
-200
5
150
-50
400
-200
I am new to R, I want to make a graph that presents the mean of each score.
whereas, the scores are lined in the Y axis, and there is a vertical line which represents the 0.
every score mean above zero a horizontal bar appears from the central to the right.
every score mean below zero a horizonal bar appears from the central to the left.
Thanks for the help!
You could achieve your desired result by first converting your dataset to long format and by computing the means per score afterwards. After these data wrangling steps you could plot the means using ggplot2 via geom_col and add a vertical zero line using geom_vline:
df <- data.frame(
ID = c(1L, 2L, 3L, 4L, 5L),
score1 = c(200L, 250L, 210L, 220L, 150L),
score.2 = c(300L, -310L, 400L, -10L, -50L),
score.3 = c(400L, -470L, 480L, -400L, 400L),
score.4 = c(-200L, -200L, -200L, -200L, -200L)
)
library(dplyr)
library(tidyr)
library(ggplot2)
df1 <- df |>
tidyr::pivot_longer(-ID, names_to = "score") |>
group_by(score) |>
summarise(value = mean(value))
ggplot(df1, aes(value, score)) +
geom_vline(xintercept = 0) +
geom_col()
EDIT To label the bars you could use geom_text. Tricky part is to align the labels. To this end I make use of an ifelse to right align (hjust = 1) the labels in case of a positive mean and left align (hjust = 0) in case of a negative mean. Actually I did 1.1 and -.1 to add some padding between the label and the bar. The axis labels could be set via the labels argument of the scale, in your case it is scale_y_discrete. Personally I prefer to use a named vector which assign labels to categories in the data.
ggplot(df1, aes(value, score)) +
geom_vline(xintercept = 0) +
geom_col() +
geom_text(aes(label = value, hjust = ifelse(value > 0, 1.1, -.1)), color = "white") +
scale_y_discrete(labels = c("score1" = "Test1", "score.2" = "Test2", "score.3" = "Test3", "score.4" = "Test4"))
Similar approach with stefan's but slightly different choice of functions:
The data:
dat <- structure(list(ID = 1:5, score1 = c(200L, 250L, 210L, 220L, 150L
), score2 = c(300L, -310L, 400L, -10L, -50L), score3 = c(400L,
-470L, 480L, -400L, 400L), score4 = c(-200L, -200L, -200L, -200L,
-200L)), class = "data.frame", row.names = c(NA, -5L))
The chain of functions
dat %>%
select(-ID) %>%
map_df(mean) %>%
pivot_longer(everything(), names_to = "score", values_to = "means") %>%
ggplot() +
coord_flip() +
geom_col(aes(x = score, y = means))
The result
In case you want to change the labels on the tick marks ("score 1", "score2", etc) to other labels, you can use scale_x_discrete.
In addition, in case you want to show the numeric value on top of each bar, you can use geom_text with hjust to adjust the label positions.
For example :
dat %>%
select(-ID) %>%
map_df(mean) %>%
pivot_longer(everything(), names_to = "score", values_to = "means") %>%
ggplot() +
coord_flip() +
geom_col(aes(x = score, y = means)) +
scale_x_discrete(labels = c("Test A", "Test B", "Test C", "Test D")) +
geom_text(aes(x = score, y = means, label = means),
hjust = c(-0.5, -0.5, -0.5, 1.1))

How to plot several columns on the same line chart in R?

my data is
year female male unknown
1929 0 50 0
1930 2 70 7
1931 0 400 1
1932 20 40 15
1933 25 120 0
I need to create a simple line chart with 3 lines where I can see gender changes over years.
I have tried something like
data <- melt(data, id.vars = 'year', variable.name = 'Gender')
ggplot(data, aes(year, value)) + geom_line(aes(colour = Gender))
but it shows me an empty chart and a comment
geom_path: Each group consists of only one observation. Do you need to
adjust the group aesthetic?
How can I create a chart where I will have three lines, one for each gender?
Also, my date is bigger than this one, it contains 92 years so when I plot something, I get a huge mess of years on the x-axis
Is there a way to somehow fix it?
With tidyverse, we pivot to 'long' format, specify the group and color with the column name 'name' column (default naming)
library(dplyr)
library(tidyr)
library(ggplot2)
data %>%
pivot_longer(cols = -year) %>%
ggplot(aes(x = year, y = value, group = name, color = name)) +
geom_line()
data
data <- structure(list(year = 1929:1933, female = c(0L, 2L, 0L, 20L,
25L), male = c(50L, 70L, 400L, 40L, 120L), unknown = c(0L, 7L,
1L, 15L, 0L)), class = "data.frame", row.names = c(NA, -5L))
How about
matplot(data$year,data[,-1], type="l")
?

How to visualize two column in bar chart using R?

I don't know if my question clear enough...
I have this table
Name Mark_Oral Mark_Written Total_M_Oral Total_M_Written
1 Hercule Poirot 50 49 858 781
2 Joe O'Neil 70 79 1056 1083
3 John McAuley 81 99 1219 1333
and I have to visualize the last two column in bar chart using R to compare student total mark
Data
table <- structure(list(Name = c("Hercule Poirot", "Joe O'Neil", "John McAuley"),
Mark_Oral = c(50L, 70L, 81L),
Mark_Written = c(49L, 79L, 99L),
Total_M_Oral = c(858L, 1056L, 1219L),
Total_M_Written = c(781L, 1083L, 1333L)),
.Names = c("Name", "Mark_Oral", "Mark_Written", "Total_M_Oral", "Total_M_Written"),
row.names = c("1", "2", "3"), class = "data.frame")
You can use + to combine other plots on the same ggplot object. For example:
ggplot(survey, aes(often_post,often_privacy)) +
geom_point() +
geom_smooth() +
geom_point(aes(frequent_read,often_privacy)) +
geom_smooth(aes(frequent_read,often_privacy))
With ggplot2 (as your tags suggest) the syntax is:
ggplot(data = table,aes(x= Total_M_Oral,y=Total_M_Written))+geom_bar(stat = "identity")
Where table is replaced by the name of your dataframe.
Edit
I was unsure that my first answer really answered your question (multiple uses of bars).
Create dummy data
df<-data.frame(x = rpois(n = 100,lambda = 800),y = rpois(n = 100,lambda = 800))
With previous plot:
If you want to count and have a color for Oral and one for written
df2<-data.frame(x = c(df$x,df$y),y = rep(c("written","oral"),each = nrow(df)))
ggplot(data = df2,aes(x= x,fill=y),alpha = I(0.5))+geom_bar(stat = "count")
Which gives:
Comment: alpha parameter is not necessary, it just deals with the transparency so that you can see when there are overlapping bars.
With student names
df3<-data.frame(name = rep(table$Name,times = 2),
y = c(table$Total_M_Oral, table$Total_M_Written),
fill = rep(c("oral","written"),each = nrow(table)))
ggplot(data = df3, aes(x = name,y= y,fill = fill,alpha = 0.5))+geom_bar(stat= "identity")

Bubble chart with ggplot with no curcle

The data of df a I use is:
x y size
589 127 16,4724409449
465 58 21,0517241379
408 58 15,9137931034
I use this to take a bubble chart
library(ggplot2)
a <- read.csv("numbers.csv", header = TRUE)
ggplot(a,aes(x,y))+geom_point(size=a$size)
but in the chart I can't see any bubble. How can I make it?
Here is the dput of a data frame:
structure(list(x = c(589L, 465L, 408L), y = c(127L, 58L, 58L),
size = structure(c(2L, 3L, 1L), .Label = c("15,9137931034",
"16,4724409449", "21,0517241379"), class = "factor")), .Names = c("x",
"y", "size"), class = "data.frame", row.names = c(NA, -3L))
Also if it possible to add names and different colours to every bubble?
x y size name
589 127 16,4724409449 nameA
465 58 21,0517241379 nameB
408 58 15,9137931034 nameC
To generate a bubble chart with size mapped to a$size, and colour and labels to a$name, we can try:
ggplot(a, aes(x, y, label = name)) +
geom_point(aes(size = size, colour = name)) +
geom_text()

Resources