Plot a character vector against a numeric vector in R
The default plot
function has a method that allows you to plot factors on the x-axis, but to use this, you have to convert your text data to a factor
:
Here is an example:
x <- letters[1:5]
y <- runif(5, 0, 5)
plot(factor(x), y)
And with your sample data:
AcceptData <- read.table(text="
Mean.Rank Sentence.Type
1 2.5 An+Sp+a
2 2.6 An+Nsp+a
3 2.1 An+Sp-a
4 3.1 An+Nsp-a
5 2.4 In+Sp+a
6 1.7 In+Nsp+a
7 3.1 In+Sp-a
8 3.0 In+Nsp-a", stringsAsFactors=FALSE)
plot(Mean.Rank~factor(Sentence.Type), AcceptData, las=2,
xlab="", main="Mean Acceptability Ranking per Sentence")
plot numeric vector with names as x ticks
You can use function axis()
to add labels. Argument xaxt="n"
inside plot()
will make plot without x axis labels (numbers).
plot(quantity,xaxt="n")
axis(1,at=1:3,labels=names(quantity))
R: Character instead of level # on x axis when plotting?
We can use xaxt = "n"
in plot
and then with axis
change the xaxis
tick labels
plot(Data ~ Months, transform(df, Months = match(row.names(df),
month.abb)), las = 2, xaxt = "n", type = "b", col = "blue")
axis(1, at = seq_len(nrow(df)), row.names(df))
GGPLOT2 Line plots from an R list containing vectors and single numeric values
This could be achieved like so:
- Convert your list of lists to a list of dataframes.
- Add a variable with your x-axis variable to each df
- Bind the list of data frames by row
- Plot, where I make use of
scale_colour_gradientn(colors = rainbow(20))
to mimic your rainbow color scale.
library(dplyr)
library(ggplot2)
models <- lapply(models, as.data.frame) %>%
lapply(function(x) { x$x <- 400:410; x}) %>%
bind_rows(.id = "id")
ggplot(models, aes(x = x, y = m, color = LAI, group = id)) +
geom_line() +
scale_x_continuous(breaks = scales::pretty_breaks()) +
scale_colour_gradientn(colors = rainbow(20))
ggplot2 dual axes plot with character vector on secondary axis
Discrete scales don't support secondary axes, see issue. That said, you can work around it by using ggh4x::guide_axis_manual()
. It's a bit of a pain where exactly the breaks should be though (I cheated by looking at the layer_data()
).
library(ggplot2)
library(ggh4x)
# df <- structure(...) # omitted for brevity
ggplot(df, aes(x=mean, y = interaction(`Unit Increase`, Exposure, sep = "&"),
colour=Models)) +
scale_color_brewer(palette="Set1",
breaks=c("Model 1","Model 2","Model 3", "Model 4")) +
geom_vline(xintercept = 1) +
geom_point(position = position_dodge(width=.75)) +
geom_errorbarh(aes(xmin = lci, xmax=uci), position=position_dodge(width=.75), height=0) +
labs(x="Odds Ratio", y="Exposures (Unit of Increase)", colour="Models") +
guides(
y = guide_axis_nested(delim = "&", n.dodge = 1),
y.sec = guide_axis_manual(
breaks = as.vector(outer(c(-0.28125, -0.09375, 0.09375, 0.28125), 1:3, "+")),
labels = df$estimates
)
) +
theme_classic() +
theme(
axis.text.y.left = element_text(margin = margin(r = 5, l = 5)),
ggh4x.axis.nesttext.y = element_text(margin = margin(r = 6, l = 6)),
ggh4x.axis.nestline.y = element_blank())
Created on 2022-05-16 by the reprex package (v2.0.1)
Shiny data frame subset based on character input converted to numerical vector
I'm not certain if this is going to resolve all issues, but I'm going to infer that the code has nested observe/reactive blocks (or something else equally not-right). Here's a working example of allowing comma-separated numbers and a submit button to subset a frame.
library(shiny)
ui <- fluidPage(
textInput("cases", "Select cases", value = ""),
actionButton("submit", "Submit", icon = icon("sync")),
tableOutput("tbl")
)
server <- function(input, output, session) {
cases <- eventReactive(input$submit, {
out <- strsplit(input$cases, ",")[[1]]
out <- suppressWarnings(as.numeric(out[nzchar(out)]))
validate(
need(!anyNA(out), "Input one or more numbers separated by commas")
)
out
})
output$tbl <- renderTable({
if (length(cases())) mtcars[cases(),] else mtcars
})
}
shinyApp(ui, server)
Notes:
Error resolution: while
out[nzchar(out)]
will silently remove empty strings caused by two consecutive commas (e.g.,1,,3
) without error, the!anyNA(out)
will cause that stop cascading reactivity, instead replacing all components that usecases()
with the stringInput one or more ...
. This means that1,,3
will work without complaint, but1,a,3
will fail and be politely noisy.This example chooses to show all rows by default. If instead you want nothing shown until there is valid input in
cases
, then replace the last reactive block here with:output$tbl <- renderTable({ mtcars[cases(),] })
Related Topics
Parallel Processing in R Limited
How Is J() Function Implemented in Data.Table
Scoping of Variables in Aes(...) Inside a Function in Ggplot
Ggplot and R: Two Variables Over Time
The Representation of an Empty Argument in a "Call"
Ggplot2: Creating Themed Title, Subtitle with Cowplot
Filling in a New Column Based on a Condition in a Data Frame
How to Print Double Quotes (") in R
Calculate Percentages of a Binary Variable by Another Variable in R
Differencebetween Short (&,|) and Long (&&, ||) Forms of And, or Logical Operators in R
Find Matches of a Vector of Strings in Another Vector of Strings
Combining More Than 2 Columns by Removing Na's in R
Why Does Mapply Not Return Date-Objects
Extract Data Between a Pattern from a Text File
How to Replace Multiple Strings with the Same in R
Sample Function Gives Different Result in Console and in Knitted Document When Seed Is Set
Data.Table := Assignments When Variable Has Same Name as a Column