在分类和数值数据框架上迭代并在R中绘制条形图

发布于 2025-01-25 20:02:37 字数 528 浏览 2 评论 0原文

我有一个数字数据帧调用a和一个cancoriacal一个调用b 对于每两个变量(一个来自b的变量,一个来自a的变量),我想绘制条形图。

我的尝试:

y <- unlist(lapply(D, Negate(is.numeric)))
x <- unlist(lapply(D, is.numeric))    
A <- D[,x]
B <- D[,y]
A <- as.data.frame(A)
B <- as.data.frame(B)

for(i in (1:ncol(A)))
{
  for(j in (1:ncol(B)))
  {
    ggplot(D, aes(x = A[,i], y = B[,j])) +
    geom_bar(fill='red') 
  }
}

但是什么都没有绘制任何东西。我不确定是否有必要将每个曲线保存在向量中,然后用另一个绘制它们。任何建议都很棒!

I have a numeric data frame call A and a categoriacal one call B
For every two variables (one from B and one from A) I want to plot a bar chart.

My try:

y <- unlist(lapply(D, Negate(is.numeric)))
x <- unlist(lapply(D, is.numeric))    
A <- D[,x]
B <- D[,y]
A <- as.data.frame(A)
B <- as.data.frame(B)

for(i in (1:ncol(A)))
{
  for(j in (1:ncol(B)))
  {
    ggplot(D, aes(x = A[,i], y = B[,j])) +
    geom_bar(fill='red') 
  }
}

But is not plotting anything. I'm not sure if it's necessary to save each plot in a vector and then plot them with another for. Any suggestions would be great!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柏林苍穹下 2025-02-01 20:02:37

您需要在print()函数中包装GGPLOT语句以在循环中生成输出:

for(i in (1:ncol(A)))
{
  for(j in (1:ncol(B)))
  {
    g<- ggplot(D, aes(x = A[,i], y = B[,j])) +
             geom_bar(fill='red') 
    print(g)
  }
}

You will need to wrap the ggplot statement inside the print() function to generate output while inside a loop:

for(i in (1:ncol(A)))
{
  for(j in (1:ncol(B)))
  {
    g<- ggplot(D, aes(x = A[,i], y = B[,j])) +
             geom_bar(fill='red') 
    print(g)
  }
}
绿萝 2025-02-01 20:02:37

我认为您需要用Geom_bar()geom_col()或添加stat = station = Insterity geom_bar(geom_bar()。

您还可以避免使用循环使用pmap from package purrr

 df <- expand.grid(
    i = 1:ncol(A),
    j = 1:ncol(B)
)

purrr::pmap(
    list(df$i, df$j),
    function(.i, .j){
        tmp <- ggplot(D, aes(x = A[,.i], y = B[,.j])) +
            geom_col(fill='red')
        print(tmp)
    }
)

我还应该补充说,您可以分配的结果pmap到对象(例如p),然后使用p [[k]]调用每个图表。

I think you need to replace geom_bar() with geom_col() or to add stat = identity inside geom_bar().

You can also avoid using the for loop by using pmap from package purrr:

 df <- expand.grid(
    i = 1:ncol(A),
    j = 1:ncol(B)
)

purrr::pmap(
    list(df$i, df$j),
    function(.i, .j){
        tmp <- ggplot(D, aes(x = A[,.i], y = B[,.j])) +
            geom_col(fill='red')
        print(tmp)
    }
)

I should also add that you can assign the result of pmap to an object (e.g. p) and then call each charts using p[[k]].

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文