Barplot in Ggplot

ggplot bar plot by multiple groups + line graph

You could use facet_wrap to plot the weeks beside each other:

 ggplot(data, aes(fill=tmp))  + 
geom_bar(aes(x=day_s, y=mpd, group=tmp) ,stat="identity") +
facet_wrap(.~tmp) +
theme_bw()

Update
To get summed up rpd as line plot you can do the following:

    library(dplyr)

rpd_sum <- data %>%
group_by(tmp, day_s) %>%
summarise(sum_rpd = sum(rpd)) %>%
mutate(newClass = paste(tmp, day_s))

data$newClass <- paste(data$tmp, data$day_s)
dataNew <- merge(data, rpd_sum )

ggplot(dataNew, aes(fill=tmp)) +
geom_bar(aes(x=day_s, y=mpd) ,stat="identity") +
geom_line(aes(x=day_s, y=sum_rpd*10, group=tmp),stat="identity") +
scale_y_continuous(sec.axis = sec_axis( trans=~./10, name="rpd Axis")) +
facet_wrap(.~tmp) +
theme_bw()

Sample Image

ggplot2 barplot with total values split into two groups

You need to rework your data set in a way that your columns name became the modalities of a variable, and all the values are in the same columns.

df<-data.frame(specie=c('apple','banana','orange'),unknow=c(1000,NA,NA),fresh=c(NA,250,700),processed=c(NA,250,150))
df <- df %>% tidyr::pivot_longer(cols = c("unknow", "fresh", "processed"),names_to = "type")

ggplot2::ggplot() +
ggplot2::geom_bar(data = df,
mapping = ggplot2::aes(x = specie,
y = value,
fill = type),
stat = "identity")

How to add text on the top of bar chart in ggplot R?

Column label was added for labeling on the plot.

BTW, the label of your desired outcome is switched. (According to your df, 89, 46.4 for Canada).

require(ggplot2)
require(dplyr)

df <- data.frame (Origin = c("Canada", "Canada","USA","USA"),
Year = c("2021", "2022","2021","2022"),
Sales = c(103, 192, 144, 210),
diff = c(89, " ",66," "),
perdiff = c(86.4, " ",45.83," "))

df <- df %>% mutate(label= ifelse(diff!=" ",paste0(diff,", ",perdiff,'%'),NA))
ggplot(df, aes(fill=Year, y=Origin, x=Sales)) +
geom_bar(position="dodge", stat="identity")+
geom_text(aes(label=label, x=200), fontface='bold') +
scale_x_continuous(breaks=seq(0,200,25))+
theme()
#> Warning: Removed 2 rows containing missing values (geom_text).

Sample Image

Created on 2022-05-03 by the reprex package (v2.0.1)

Order Bars in ggplot2 bar graph

The key with ordering is to set the levels of the factor in the order you want. An ordered factor is not required; the extra information in an ordered factor isn't necessary and if these data are being used in any statistical model, the wrong parametrisation might result — polynomial contrasts aren't right for nominal data such as this.

## set the levels in order we want
theTable <- within(theTable,
Position <- factor(Position,
levels=names(sort(table(Position),
decreasing=TRUE))))
## plot
ggplot(theTable,aes(x=Position))+geom_bar(binwidth=1)

barplot figure

In the most general sense, we simply need to set the factor levels to be in the desired order. If left unspecified, the levels of a factor will be sorted alphabetically. You can also specify the level order within the call to factor as above, and other ways are possible as well.

theTable$Position <- factor(theTable$Position, levels = c(...))

How can I add hatches, stripes or another pattern or texture to a barplot in ggplot?

One approach is to use the ggpattern package written by Mike FC (no affiliation):

library(ggplot2)
#remotes::install_github("coolbutuseless/ggpattern")
library(ggpattern)
ggplot(data = df, aes(x = Class, fill = StudyTime, pattern = Nerd)) +
geom_bar_pattern(position = position_dodge(preserve = "single"),
color = "black",
pattern_fill = "black",
pattern_angle = 45,
pattern_density = 0.1,
pattern_spacing = 0.025,
pattern_key_scale_factor = 0.6) +
scale_fill_manual(values = colorRampPalette(c("#0066CC","#FFFFFF","#FF8C00"))(4)) +
scale_pattern_manual(values = c(Nerd = "stripe", NotNerd = "none")) +
labs(x = "Class", y = "Number of Students", pattern = "Nerd?") +
guides(pattern = guide_legend(override.aes = list(fill = "white")),
fill = guide_legend(override.aes = list(pattern = "none")))

Sample Image

The package appears to support a number of common geometries. Here is an example of using geom_tile to combine a continuous variable with a categorical variable:

set.seed(40)
df2 <- data.frame(Row = rep(1:9,times=9), Column = rep(1:9,each=9),
Evaporation = runif(81,50,100),
TreeCover = sample(c("Yes", "No"), 81, prob = c(0.3,0.7), replace = TRUE))

ggplot(data=df2, aes(x=as.factor(Row), y=as.factor(Column),
pattern = TreeCover, fill= Evaporation)) +
geom_tile_pattern(pattern_color = NA,
pattern_fill = "black",
pattern_angle = 45,
pattern_density = 0.5,
pattern_spacing = 0.025,
pattern_key_scale_factor = 1) +
scale_pattern_manual(values = c(Yes = "circle", No = "none")) +
scale_fill_gradient(low="#0066CC", high="#FF8C00") +
coord_equal() +
labs(x = "Row",y = "Column") +
guides(pattern = guide_legend(override.aes = list(fill = "white")))

Sample Image

R bar-plot with different columns on the x-axis

The best way to achieve this is to reshape your dataset long, and then use position_dodge to separate the bars corresponding to different times. So:

library(ggplot2)
library(tidyr)
dat %>%
pivot_longer(cols=-c(Id,Time)) %>%
ggplot(aes(x=name, y=value, fill=Time, group=Time)) +
stat_summary(geom="col",width=0.8,position=position_dodge()) +
stat_summary(geom="errorbar",width=0.2,position=position_dodge(width=0.8))

Sample Image

Consider also adding the data points for extra transparency. It will be easier for your readers to understand the data and judge its meaning if they can see the individual points:

dat %>% 
pivot_longer(cols=-c(Id,Time)) %>%
ggplot(aes(x=name, y=value, fill=Time, group=Time)) +
stat_summary(geom="col",width=0.8,position=position_dodge()) +
stat_summary(geom="errorbar",width=0.2,position=position_dodge(width=0.8)) +
geom_point(position = position_dodge(width=0.8))

Sample Image

In response to the comment requesting re-ordering of factors and specifying colours, I have added a line to transform Time to a factor while specifying the order, specifying the limits for the x-axis to set the order of the groups, and using scale_fill_manual to set the colours for the bars.

dat %>% 
mutate(Time = factor(Time, levels=c("pre", "post"))) %>%
pivot_longer(cols=-c(Id,Time)) %>%
ggplot(aes(x=name, y=value, fill=Time, group=Time)) +
stat_summary(geom="col",width=0.8,position=position_dodge()) +
stat_summary(geom="errorbar",width=0.2,position=position_dodge(width=0.8)) +
geom_point(position = position_dodge(width=0.8)) +
scale_x_discrete(limits=c("Tyr1", "Tyr2", "Baseline")) +
scale_fill_manual(values = c(`pre`="lightgrey", post="darkgrey"))

Sample Image

To understand what is happening with the reshape, the intermediate dataset looks like this:

> dat %>% 
+ pivot_longer(cols=-c(Id,Time))
# A tibble: 18 x 4
Id Time name value
<int> <chr> <chr> <dbl>
1 1 pre Baseline 0.536
2 1 pre Tyr1 0.172
3 1 pre Tyr2 0.141
4 2 post Baseline 0.428
5 2 post Tyr1 0.046
6 2 post Tyr2 0.084
7 3 pre Baseline 0.077
8 3 pre Tyr1 0.015
9 3 pre Tyr2 0.063
10 4 post Baseline 0.2
11 4 post Tyr1 0.052
12 4 post Tyr2 0.041
13 5 pre Baseline 0.161
14 5 pre Tyr1 0.058
15 5 pre Tyr2 0.039
16 6 post Baseline 0.219
17 6 post Tyr1 0.059
18 6 post Tyr2 0.05

Stacked bar plot with ggplot2

You should add rownames as a variable in your data frame, and transform your data to long format so ggplot can handle it. Something like this is close to what you mean I think:

yourDataFrame %>% 
mutate(Label = rownames(df)) %>% # add row names as a variable
reshape2::melt(.) %>% # melt to long format
ggplot(., aes(x = Label, y = value, fill = variable)) +
geom_bar(stat='identity')

Barplot in ggplot

To plot a bar chart in ggplot2, you have to use geom="bar" or geom_bar. Have you tried any of the geom_bar example on the ggplot2 website?

To get your example to work, try the following:

  • ggplot needs a data.frame as input. So convert your input data into a data.frame.
  • map your data to aesthetics on the plot using `aes(x=x, y=y). This tells ggplot which columns in the data to map to which elements on the chart.
  • Use geom_plot to create the bar chart. In this case, you probably want to tell ggplot that the data is already summarised using stat="identity", since the default is to create a histogram.

(Note that the function barplot that you used in your example is part of base R graphics, not ggplot.)

The code:

d <- data.frame(x=1:10, y=1/(10:1))
ggplot(d, aes(x, y)) + geom_bar(stat="identity")

Sample Image

How can I bar plot a dataframe with ggplot2?

As @RuiBarradas has already pointed out, you want to change the rownames into a column, which we can do with tibble::rownames_to_column. Here, I also provide some additional options to further customize the chart. I chose a light hue to fill each bar with. I converted the scientific notation, but if you want the scientific notation along the y-axis, then you can remove the last line here (i.e., scale_y_continuous(labels = comma)).

library(tidyverse)
require(scales)

df.MontosTipo %>%
tibble::rownames_to_column("nombres.MontosTipo") %>%
ggplot(aes(x = nombres.MontosTipo, y = `Montos totales`, fill = factor(`Montos totales`))) +
geom_col( ) +
scale_fill_hue(c = 40) +
theme_bw() +
theme(legend.position="none") +
xlab("Nombres") +
ylab("Montos Totales") +
scale_y_continuous(labels = comma)

Output

Sample Image

Data

df.MontosTipo <-
structure(
list(`Montos totales` = c(1617682625, 248738139)),
row.names = c("Tipo de moneda 1",
"Tipo de moneda 2"),
class = "data.frame"
)


Related Topics



Leave a reply



Submit