微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Julia's Gadfly 中按升序或降序对条形图进行排序? 有没有人知道一种不那么hacky的方式?

如何解决如何在 Julia's Gadfly 中按升序或降序对条形图进行排序? 有没有人知道一种不那么hacky的方式?

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

解决方法

我的黑客是这样的:

using DataFrames
using DataStructures
using Gadfly

# test data
list = ["E","E","B","C","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")

有没有人知道一种更简洁的方法来做到这一点?

,
df = DataFrame(
list = ["E","A"]
)


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

enter image description here

Gadfly tutorial

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。