添加自定义颜色以进行图表切片

时间:2018-10-29 18:45:06

标签: go colors pie-chart

我无法在饼图切片中添加自定义颜色。我正在使用转到图表库,不确定如何在图表中动态添加自定义颜色。

在这里,我正在使用此代码处理图形,我知道我们有一个图表样式选项,可以使用drawing.Color{R,G,B,A}来分配颜色,但这将仅对所有切片指定一种颜色。我想为每个饼图切片动态指定自己的自定义颜色

   raw := `{"reaction_summary": {"ANGRY": 7,"HAHA": 40,"LIKE": 161,"LOVE": 56,"SAD": 26,"SHOCK": 6}}`

// Parse JSON
data := struct {
    ReactionSummary map[string]int `json:"reaction_summary"`
}{}
if err := json.Unmarshal([]byte(raw), &data); err != nil {
    log.Fatal(err)
}
// Populate a slice of chart values
var values []chart.Value
for l, v := range data.ReactionSummary {
    values = append(values, chart.Value{Label: l, Value: float64(v)})
}
// Initialize the chart
pie := chart.PieChart{
    Width:  512,
    Height: 512,
    Values: values,
}

Pie chart here

1 个答案:

答案 0 :(得分:0)

请参见以下示例:https://github.com/wcharczuk/go-chart/blob/master/_examples/custom_styles/main.go

对于您的每个chart.Value{Label: l, Value: float64(v)},您可以提供一个Style属性:https://godoc.org/github.com/wcharczuk/go-chart#Value

style属性可以包含颜色,笔触和其他内容:

Style: chart.Style{
    Show:        true,                           //note; if we set ANY other properties, we must set this to true.
    StrokeColor: drawing.ColorRed,               // will supercede defaults
    FillColor:   drawing.ColorRed.WithAlpha(64), // will supercede defaults
},

此处有更多选项:https://godoc.org/github.com/wcharczuk/go-chart#Style

请确保将来链接到您正在使用的库。

如果要使用JSON中的自定义颜色,请使用json字符串中的RGB值并将其解析为结构,或者在代码中的结构中定义颜色并使用传递的值。