logo
Tags down

shadow

Manually add labels separately (or together) by factor levels to barplot ggplot


By : giterwen
Date : September 14 2020, 11:00 PM
this will help Your code as posted didn't work in the second example, because factor2 was length 3, and ggplot2 doesn't automatically recycle the same way R does. Another problem with your code is that you specified a y value of 45, which is way above the maximum len observed. By scaling this relative to the max observed len (I chose max(len) / 5 but that's arbitrary), it'll always be visible (assuming you don't have negative values...).
code :
library("ggplot2")    
df <- data.frame(
  supp = rep(c("A", "B"), each = 3),
  dose = rep(c("D1", "D2", "D3"), 2),
  len = c(2, 4, 3, 15, 40, 29.5),
  factor2 = c("Dose I.", "Dose II.", "Dose III.")
)


ggplot(
    data = df,
    aes(x = dose, y = len, fill = supp)
  ) +
  geom_bar(stat = "identity", position = position_dodge()) +
  geom_text(
    aes(label = len),
    position = position_dodge(0.9), 
    vjust = c(-1.6, 1.6, -1.6, 1.6, -1.6, 1.6), 
    color = "black",
    size = 3.5) +
  geom_label(aes(x = dose, y = max(len) / 5, label = factor2), inherit.aes = FALSE, 
    color = "black",
    fill = "white",
    fontface = "bold",
    size = 3
  )


Share : facebook icon twitter icon

Cleaning up factor levels (collapsing multiple levels/labels)


By : mchinlai
Date : March 29 2020, 07:55 AM
it helps some times UPDATE 2: See Uwe's answer which shows the new "tidyverse" way of doing this, which is quickly becoming the standard.
UPDATE 1: Duplicated labels (but not levels!) are now indeed allowed (per my comment above); see Tim's answer.
code :
x <- c("Y", "Y", "Yes", "N", "No", "H", NA)
x <- factor(x)
levels(x) <- list("Yes"=c("Y", "Yes"), "No"=c("N", "No"))
x
## [1] Yes  Yes  Yes  No   No   <NA>  <NA>
## Levels: Yes No
> `levels<-`(factor(x), list(Yes=c("Y", "Yes"), No=c("N", "No")))
[1] Yes  Yes  Yes  No   No   <NA>
Levels: Yes No

R ggplot barplot separately for each year


By : user2802763
Date : March 29 2020, 07:55 AM
I hope this helps . I would like to know how to get a barplot where data are separately for each year. I'd like to add an Excel-image, but I couldn't cause I'm new in this forum. I have following data in a data frame: , Not sure if this is what you are looking for..
code :
dat <- structure(list(var = structure(1:7, .Label = c("V1", "V2", "V3",  "V4", "V5", "V6", "V7"), class = "factor"), `2009` = c(-221.85, 0, 0, 0, 0, 0, 0), `2010` = c(0, -223.16, -1216.17, -520.87, -465.48, -496.25, 0), `2011` = c(0, -231.52, -1337.28, -540.88, -805.63, 0, 0), `2012` = c(-138.73, 0, -1112.11, -174.85, -252.38, 0, -709.63), `2013` = c(-191.1, -126.85, -863.98, -296.78, -178.92, -232.17, -759.41)), .Names = c("var", "2009", "2010", "2011", "2012", "2013"), class = "data.frame", row.names = c(NA, -7L))

library(ggplot2)
library(reshape2)

names(dat) <- c("var", "2009", "2010", "2011", "2012", "2013")
dat.m <- melt(dat)
ggplot(dat.m, aes(x=variable, y=value, fill=var)) + geom_bar(position="dodge", stat="identity")

Factor unknown levels at runtime while setting labels for known levels at design time


By : user3491529
Date : March 29 2020, 07:55 AM
this will help Consider a simple function that factors and labels a vector (with unordered levels): , You could do
code :
  my.factor <- function(data){
    levels <- c("d1", "d2", "d3")
    labels <- c("Data 1", "Data 2", "Data 3")
    nlevels <- setdiff(unique(data), levels)
    levels<-c(levels, nlevels)
    labels <-c(labels, nlevels)
    factored.data = factor(data, levels, labels)
    factored.data
  }
data = c("d1", "d2", "d3", "d1", "d100")
my.factor(data)
# [1] Data 1 Data 2 Data 3 Data 1 d100  
# Levels: Data 1 Data 2 Data 3 d100

Sorting a ggplot axis' factor according to another factor's levels


By : priya
Date : March 29 2020, 07:55 AM
it helps some times I like the facet idea in Ulrik's answer - that will probably be the nicest visualization. To order the factor levels of the neighbourhood column the easiest way is probably like this:
code :
# order the data frame as desired
df = df[order(df$district, df$neighbourhood), ]
# set the neighbourhood levels in the order the occur in the data frame
df$neighbourhood = factor(df$neighbourhood, levels = unique(df$neighbourhood))

How to Make a Grouped Barplot for a Factor with Many Levels


By : RJ Lucas
Date : March 29 2020, 07:55 AM
seems to work fine Assuming you want to plot means of Canopy_Index for each Under_Open, Topography cell, you can form means first:
code :
df.means <- aggregate(Canopy_Index ~ Under_Open + Topography, df.melt, mean)
ggplot(df.means, aes(x=Topography, y=Canopy_Index, fill=Under_Open)) +
  geom_bar(stat="identity", position="dodge") +
  scale_fill_discrete(name="Canopy Type",
         labels=c("Under_tree"="Under Canopy", "Open_Canopy"="Open Canopy")) +
  xlab("Topographical Feature") + ylab("Canopy Index")
df.max <- aggregate(Canopy_Index ~ Under_Open + Topography, df.melt, max)
# Under_Open         Topography Canopy_Index
# 1   Under_tree Artificial_Surface           75
# 2  Open_Canopy Artificial_Surface           95
# 3   Under_tree          Bare_soil           95
# 4  Open_Canopy          Bare_soil           95
# 5   Under_tree              Grass           95
# 6  Open_Canopy              Grass           95
# 7   Under_tree             Litter           95
# 8  Open_Canopy             Litter           95
# 9   Under_tree        Undergrowth           95
# 10 Open_Canopy        Undergrowth           95
Related Posts Related Posts :
  • 45 degree line and same coordinate lengths in scatter plot in R
  • Mapping multiple columns in R including a single column containing comma-separated values
  • How to unscale Neural Network Predictions
  • R : Merge several dataframes from a list into a single dataframe with differentiation between dataframes
  • How to remove value to the front of the data.frame in R
  • How to print the corresponding ID to the max() value
  • Converting a column of integers that aren't in date format already into abbreviated months
  • Coerce column values to column names and condense repeat observations in R
  • How to replace values in the columns of a dataframe based on the values in the other column in R?
  • What can't I do with dtplyr that I can in data.table
  • How to replace NA value with previous non NA value given to same ID
  • Using Regex to find the characters '!' and '?' in a string
  • R : How to join several lists of a single element into a single list of an element
  • Calculating an average using tidyverse
  • Calculating category specific variable in R
  • lm()-function gives different results on SolusOS Linux than on Windows
  • Mark a period of time in a time-series-plot
  • how to execute function over the data frame
  • Add unique rows to dataframe (opposite of intersect)
  • Convert vector element in tibble to expand
  • Storing lists with different values inside a for loop R
  • Pasting 2 columns to a new variable in a ordered format
  • R - How to collapse rows of dataframe taking the max of each column for each unique id
  • How to render ggplot2+gganimate+ggflags faster
  • R and ggplot: shade the color of the categorical variable
  • How to return a server object in Ui?
  • How can I efficiently group several columns into one list column in data.table
  • Working with transform and mutate in tidyverse to calculate a cumulative sum
  • Sort a vector using a "personalised" order in R
  • Can we log individual user details in R Shiny if i host my application from my pc as server?
  • subtract a different vector from each row in a matrix in r
  • Why is data.table slower than base R for these lookup table-style queries?
  • How to customize the content of a legend of a dotplot with ggplot2
  • What is wrong w/ this boxplot?
  • Merge 2 csv files into one with different columns in R
  • How to avoid loop in *multiplication of multiple rows in data frame
  • Add lateral facets to a dotplot with multiple values for variables
  • Looping over multiple data frames to ggplot
  • Using a for loop to create new datasets in the environment
  • What's the shortest code to generate the below matrices in R?
  • split the superhero names with their ages in the given vector
  • Excluding NA and odd number
  • R: how to assign seasons to months (factor)
  • R: plotting sky map in Mollweide projection in galactic coordinate system
  • Split rows to columns in R
  • Mutate with column value >0
  • Equivalent function to excel's replace
  • R: Unusual error plotting multipolygons with ggplot, geom_sf, and openstreetmap
  • group by text in columns, look for common entries in two data frames
  • How can I remove NAs when both columns are missing only?
  • Fill up a list using an existing vector and a double for loop
  • Count frequency of events in R
  • Replace value in dataframe by value divided by mean of the entire column
  • How to update selected rows in a data.table if they match value from another data.table
  • concatenate iteratively first/last n words from strings
  • Form a vector A of length 100 whose odd and even position value will be 2 and 3, respectively
  • How to create a Qrcode list of names in r
  • How to subset a dataframe by unique character in R?
  • How to select a nested field with bigrquery using dplyr syntax?
  • look for common entries in two data frames
  • shadow
    Privacy Policy - Terms - Contact Us © 35dp-dentalpractice.co.uk