1

我制作了一个 dict-of-counts 风格的 df 来制作一个条形图,并且有兴趣按大小按降序对条形进行排序。在 R 世界中,我会做这样的事情并且想知道 1) 这样做会有什么整洁的方法,以及 2) 如果在 Gadfly 中存在类似的东西。

4

2 回答 2

1
df = DataFrame(
list = ["E", "E", "E", "E", "E","B", "B", "B", "B",
    "C", "C", "C", "D", "D", "D","A"]
)


p1 = plot(df, x=:list, Geom.histogram)
p2 = plot(df, x=:list, Geom.histogram,  Scale.x_discrete(levels=["A","D","C","B","E"]) )

在此处输入图像描述

请参阅牛虻教程

于 2021-03-26T14:19:52.940 回答
1

我的黑客是这样的:

using DataFrames
using DataStructures
using Gadfly

# test data
list = ["E", "E", "E", "E", "E",
        "B", "B", "B", "B",
        "C", "C", "C",
        "D", "D", "D",
        "A"]

# I am making a dict-of-counts to turn into a df
# empty string->int dict
countsDict = Dict{String,Integer}()

# a function to count occurences of a given string in an array
function countStrInArray(str::String, arr::Array{String,1})::Integer
    findall(x -> x == str, arr) |> length
end

# for every item in the list 
for item in list
    # if we don't have it in the dict, add, with count as value
    if !haskey(countsDict, item)
        countsDict[item] = countStrInArray(item, list)
    end
end

# this gives me the structure I want but I lose 'lookup' functionality
sortedTuples = sort(collect(zip(values(countsDict),
                    keys(countsDict))), rev = true)

# ...so I creaated an order-preserving dict
sortedCountsDict = OrderedDict{String,Integer}()

# map our tuples to it
for item in sortedTuples
    sortedCountsDict[item[2]] = item[1]
end

# make it into a dataframe
df = DataFrame(group = [i for i in keys(sortedCountsDict)],
               count = [i for i in values(sortedCountsDict)])
# plot it!
plot(df, x = :group, y = :count, Geom.bar) |> SVG("HackyButWorks.svg")

有谁知道更清洁的方法来做到这一点?

于 2021-03-22T15:55:19.213 回答