José
José

Reputation: 3

Plotting in R with numerical and nonnumerical variables

EDIT: THIS is what I want my bar plot to look like – I managed to do it on JMP, and I'd like help doing it in R. Thanks!

I'm trying to create a plot on R. There are 2 variables (columns) of interest: "TrialType" and "SMTscenes.RESP" — TrialType's values are either "Old" or "New", whereas SMT~'s values are either "1", "2", "3", "4", or "r". That's right, that "r" isn't a 5, which makes this a bit frustrating.

hist(c(df$TrialType, df$SMTscenes.RESP))

is what I've tried so far, and that gives me this histogram, which does not display the difference between "Old" and "New" – or if it does, it is not all that clear to me.

At others' suggestions (previously), I've done:

table(c(df$SMTscenes.RESP, df$TrialType))

which outputs:

1 2 3 4 5 80 150 25 17 16

And now the previous histogram's form makes sense – but that's not what I'm looking for.

Let me know if there is other info/data I can provide. If so, let me know how to upload a .csv file.

Thanks in advance!

Upvotes: 0

Views: 65

Answers (2)

PavoDive
PavoDive

Reputation: 6496

First off, you really need to improve your question.

Then, you can achieve what you want with the help of two packages: data.table and ggplot2:

# create dummy data (next time, provide some, please!)
set.seed(1)
a <- data.frame(scenes= sample(c("1","2","3","4","r"),20,TRUE),
                type=sample(c("New","Old"),20, TRUE))

# load packages
library(data.table)
library(ggplot2)

# convert data frame to data table
setDT(a)

# generate counts:
b <- a[, .N, by=.(scenes, type)]

# generate plot:
ggplot(b, aes(x=type, y=N))+
     geom_bar(stat = "identity")+
     facet_wrap(facets = "scenes")

.N in the data table call creates a new variable with the counts. by= defines the groupings you want.

Upvotes: 0

Icaro Bombonato
Icaro Bombonato

Reputation: 4172

Here is a good starting point. You just need to customize the appearance now:

scene1 <- c(rep(x = c("new"), 10), rep(x = c("old"), 2))
scene2 <- c(rep(x = c("new"), 60), rep(x = c("old"), 20))
scene3 <- c(rep(x = c("new"), 5), rep(x = c("old"), 20))
scene4 <- c(rep(x = c("new"), 2), rep(x = c("old"), 18))
sceneR <- c(rep(x = c("new"), 0), rep(x = c("old"), 18))

TrialType <- c(
  rep("1", length(scene1)), 
  rep("2", length(scene2)), 
  rep("3", length(scene3)), 
  rep("4", length(scene4)), 
  rep("r", length(sceneR)))

SMTscenes.RESP <- c(
  scene1,
  scene2,
  scene3,
  scene4,
  sceneR
)

df <- data.frame(TrialType, SMTscenes.RESP)

library(ggplot2)

ggplot(data = df, aes(SMTscenes.RESP)) +
  geom_bar() +
  facet_grid(. ~ TrialType)

Plot

Upvotes: 1

Related Questions