使用ggplot在dame时间重叠线条和条形图

时间:2018-03-31 16:59:31

标签: r ggplot2

想要在条形图上用ggplot重叠折线图。 比如说,V1,V2是条形图的数据,V3应该表示为线。 如何同时完成子集和不同的geom?

class Solution {
public:
    int threeSumClosest(vector<int>& nums, int target) {
        sort(nums.begin(), nums.end());
        int ans = nums[0] + nums[1] + nums[2];
        for(int i = 0; i < nums.size() - 2; i++) {
            int l = i + 1, r = nums.size() - 1;

            while (l < r) {
                if(abs(nums[i] + nums[l] + nums[r] - target) < abs(target - ans)) {
                    ans = nums[i] + nums[l] + nums[r];
                }
                if(nums[r] + nums[l] > target - nums[i]) r = r - 1;
                else l = l + 1;
            }
        }
        return ans;
    }
};

会是这样的吗?

library(data.table)
library(ggplot2)
set.seed(100)
dat <- data.frame(Axis=letters[1:10],V1=1:10, V2=runif(10, 1,10), V3=10:1)
dat <-melt(data,id.var="Axis",measure.var=c("V1","V2","V3"))

我尝试制作V1,V2的子集并制作条形图,但不能将V3作为图表中的一条线。

非常感谢

感谢@ dash2,我略微改变了他的代码,让它看起来更清晰。

ggplot(dat, aes(x=Axis)) + 
geom_bar(stat="identity", aes(, y= value[------]))+   # V1, V2 for bars
geom_line(aes(y=value[-----))                         # V3 for line

enter image description here

4 个答案:

答案 0 :(得分:1)

无需melt您的数据,只需为每个geom添加不同的美学:

data <- data.frame(Axis=letters[1:10], V1=1:10, V2=runif(10, 1,10), V3=10:1)

ggplot(data, aes(x = V1)) +
  geom_col(aes(y = V2)) +
  geom_line(aes(y = V3))

Plot

答案 1 :(得分:1)

这个怎么样

library(data.table)
library(ggplot2)
set.seed(100)
data <- tibble(Axis=letters[1:10],V1=1:10, V2=runif(10, 1,10), V3=10:1)
data <-melt(data,id.var="Axis",measure.var=c("V1","V2","V3"))
glimpse(data)
ggplot(data, aes(x=Axis, y= data$value)) +
  geom_bar(aes(fill = variable), stat="identity")

enter image description here

答案 2 :(得分:1)

另一个选项可能是melt数据:

library(data.table)
library(ggplot2)
set.seed(100)
data <- data.frame(Axis=letters[1:10],V1=1:10, V2=runif(10, 1,10), V3=10:1)
data <-melt(data,id.var="Axis",measure.var=c("V1","V2","V3"))

library(dplyr)
ggplot() +
geom_bar(data=filter(data, variable %in% c("V1", "V2")), 
 aes(x = Axis, y = value, fill=variable), stat ="identity", position="dodge") +
  geom_line(data=filter(data, variable == "V3"), 
      aes(x = Axis, y = value, colour = variable, group=variable))

enter image description here

答案 3 :(得分:1)

最简单,没有融化。

bin/saxon --repo repo data.xml test.xslt

enter image description here

增添美感。

<?xml version="1.0" encoding="utf-8"?> <result> <url> <orig>http://python.org</orig> <location>https://python.org/</location> </url> <url> <orig>http://stackoverflow.com</orig> <location>https://stackoverflow.com/</location> </url> </result> 参数是必要的。我认为离散比例(比如这里的x轴)会自动对它们的值进行分组,让你得到1组,没有画线......一致但不直观。