在饼图切片中添加自定义颜色时遇到问题。我正在使用go图表库,不知道如何在图表中动态添加自定义颜色。
在这里,我正在使用此代码处理一个图表,我知道我们有一个图表样式选项来使用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,
}
此处为饼图
请参阅此示例: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: 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值并将其解析为结构,或者在代码中的结构中定义颜色并使用传递的值。