【问题标题】:Plotting two lists in Clojure在 Clojure 中绘制两个列表
【发布时间】:2018-10-02 13:30:23
【问题描述】:

我有两个列表。例如:列表 A 是 [1 2 3 2 2 1],列表 B 是 [1.2 2.2 1 1 1 1]。我想在 x 轴上拥有列表 A 的唯一编号以及列表 B 中相应条目的总和。例如:对于上面的示例,我想绘制 {(1,2.2),(2,4.2), (3,1)} 作为直方图(不是散点图)。

我的要求包括两个步骤。

  1. 首先将列表 B 中的值与列表 A 中的每个唯一值相加
  2. 将这些总和与列表 A 中的相应值绘制为直方图。

你能帮帮我吗?

编辑: 这是我的尝试,基于我从阅读 SO 上的其他答案中所能理解的一点:

(def A [1 2 3 2 1])
(def B [1.2 2.3 2 1 1])
(for [x (distinct A)] (map first 
           (filter #(= (second %) x)
                   (map-indexed vector A))))
;; This gives the indices for each unique element in A
;; In this case, it gives ((0 4) (1 3) (2))

我无法弄清楚如何找到如何从列表 B 中获取相应的总和。我尝试了以下方法,但它不起作用。

(apply nth B (map first 
           (filter #(= (second %) 1)
                   (map-indexed vector A))) )
;; In this case, it gives on the first element i.e. 1.2

如您所见,我是 Clojure 和函数式编程语言的新手。您能否指出一些解决了类似问题的示例?

提前致谢。

编辑: 第一个任务的最终解决方案:

(for [x (distinct A)]     (reduce + 0.0 (map #(nth B %) (map first 
               (filter #(= (second %) x)
                       (map-indexed vector A))) )  )         )
    ;; This gives me the correct output (2.2 3.3 2.0)

P.S:我不明白使用(map #(nth B%)..这个概念。我只是从其他例子中偶然发现的。

【问题讨论】:

  • 到目前为止你尝试过什么?
  • @m0skit0:对于第二个任务,我想我必须使用 (plot/list-plot ...)。我试过(plot/list-plot list A listC),列表C在哪里是第一个任务的输出。我对第一项任务一无所知。如果您至少可以指导已回答的类似问题,我将不胜感激。
  • 我建议您编辑您的问题并显示您目前拥有的代码。我认为第一个任务相对简单,您至少可以尝试一下 :)
  • @m0skit0:我的尝试更新了。
  • 如果我理解正确的话,我认为您提供的预期结果列表是错误的,最后一个元素不应该是(3 4)吗?

标签: clojure


【解决方案1】:

对于第一个任务,我想这种方式要简单一些:

(def A [1 2 3 2  2 1])
(def B [1.2 2.2 1 1 1 1])
(def C
  (reduce (partial merge-with +)
          (map hash-map A B))) ; Vector of key-values [{1 1.2} {2 2.2} ...]
; {1 2.2, 2 4.2, 3 1}

对于第二个任务,有许多图表库选项。我以clj-xchart为例:

(require '[com.hypirion.clj-xchart :as c])

(let [x-values (keys C)
      min-x (apply min x-values)
      max-x (apply max x-values)]
  (c/view
    (c/category-chart
      {"C" C}
      {:title "Example"
       :legend {:visible? false}
       :x-axis {:order (range min-x max-x)}
       :theme :ggplot2})))

最后的情节:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 2016-04-13
    相关资源
    最近更新 更多