如何按数字顺序放置图例名称
我正在处理以数字结尾的字符串,并希望将字符串按数字图例的数字顺序排列。
# Example dataframe
d <- data.frame(
SampleID = sprintf("sample_%s", rep(10:39)),
Variable = 1:30,
Group = append(rep("group_1", each = 15), rep("group_2", each = 15)),
Group1 = runif(30, min=0, max=100),
Group2 = runif(30, min=0, max=100)
)
# Character level I add to give each animal unique shape
d$Animals <- sprintf("Animal_%s",rep(c(1:10), each = 3))
library(ggplot2)
# Plot
ggplot(d, aes(Group1, Group2, color=Group, shape=Animals)) +
xlab(paste0("Value 1")) +
ylab(paste0("Value 2")) +
coord_fixed() +
geom_point() +
scale_shape_manual(values=c(0:10))
I am working with strings that end with a number and would like to put the strings in numerical order for the figure legend.
# Example dataframe
d <- data.frame(
SampleID = sprintf("sample_%s", rep(10:39)),
Variable = 1:30,
Group = append(rep("group_1", each = 15), rep("group_2", each = 15)),
Group1 = runif(30, min=0, max=100),
Group2 = runif(30, min=0, max=100)
)
# Character level I add to give each animal unique shape
d$Animals <- sprintf("Animal_%s",rep(c(1:10), each = 3))
library(ggplot2)
# Plot
ggplot(d, aes(Group1, Group2, color=Group, shape=Animals)) +
xlab(paste0("Value 1")) +
ylab(paste0("Value 2")) +
coord_fixed() +
geom_point() +
scale_shape_manual(values=c(0:10))
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以将 Animal 变量转换为有序且水平的因子
You can make the convert the Animal variable into an ordered and leveled factor
如果因子数量太大,则接受的解决方案不可行,因为它需要以正确的顺序手动输入因子级别。如果原始数据排序不正确,建议的另一个解决方案(使用
unique(d$Animals)
以正确的顺序获取级别)也可能会失败。如果有人需要更通用的解决方案(这是一个非常常见的问题),您可以使用这将根据字符串中找到的第一个数字正确地重新排序级别,无论是 10 还是 1000 个级别以及它们在数据集中出现的顺序。
The accepted solution is not viable if the number of factors is too large as it requires manually typing the factor levels in the correct order. The other solution proposed (using
unique(d$Animals)
to get the levels in the correct order) also may fail if the original data is incorrectly ordered. In case someone needs a more general solution (this is a very common problem) you can useThis will properly reorder the levels according to the first number found in the string regardless of being 10 or 1000 levels and the order they appear in your dataset.
谢谢@Susan Switzer,我会接受这个答案,但是我对你原来的解决方案做了一些小小的改变。
Thank you @Susan Switzer, I'll accept this answer, however I made a slight change to your original solution.