Reputation: 31
I am trying to use plotly
to plot a bar chart with strings (combination number) as x-axis.
("1", "2", "3", "4 - 5", "6 - 8","9 - 13", "14 - 21", "22 - 34", "35 - 55")
However, Only 3 data is being ploted. ("1", "2", "3")
Here is the code:
library(plotly)
dfb = structure(groups = c("1", "2", "3", "4 - 5", "6 - 8",
"9 - 13", "14 - 21", "22 - 34", "35 - 55"),
counts = c(29090,10074, 4573, 4029, 2289, 1120, 337, 78, 15)),
class = c("data.frame"),
row.names = c(NA,-9L),
.Names = c("groups","counts")
)
plot_ly(dfb,
x = groups,
y = counts,
type = "bar")
returns:
But if I filtered on of groups that contain only numbers, it is working well:
dfc=subset(dfb,dfb$groups!='1')
plot_ly(dfc,
x = groups,
y = counts,
type = "bar")
Why is this happening? And how to solve this?
I'm using plotly because I want to used it with Shiny, and for now it is the most fit for me.
I didn't use ggplotly (make ggplot and then convert it to plotly) because sometimes axis tittle being cut off.
Upvotes: 3
Views: 2653
Reputation: 1326
I'm afraid this is a duplicated question: Plotly R: Cant get points to plot when two values present per x factor level. However here you have a couple of solutions:
Solution 1 (also proposed in the referred question):
library(plotly)
dfb = data.frame(groups= c("1", "2", "3", "4 - 5", "6 - 8","9 - 13", "14 - 21", "22 - 34", "35 - 55"),
counts=c(29090,10074, 4573, 4029, 2289, 1120, 337, 78, 15))
plot_ly(dfb,
x = groups,
y = counts,
type = "bar") %>%
layout(xaxis=list(type='category'))
Solution 2 (way less elegant)
groups_str <- c("1", "2", "3", "4 - 5", "6 - 8","9 - 13", "14 - 21", "22 - 34", "35 - 55")
groups <- 1:length(groups_str)
dfb = data.frame(groups= groups,
counts=c(29090,10074, 4573, 4029, 2289, 1120, 337, 78, 15))
plot_ly(dfb,
x = groups,
y = counts,
type = "bar") %>%
layout(xaxis=list(tickmode='array', tickvals=groups, ticktext=groups_str))
Both produce the figure (with different xaxis title, though)
Upvotes: 2