utils.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265
  1. package charter
  2. import (
  3. "bytes"
  4. "encoding/base64"
  5. "fmt"
  6. "math/rand"
  7. "os"
  8. "time"
  9. "github.com/wcharczuk/go-chart"
  10. "github.com/wcharczuk/go-chart/drawing"
  11. )
  12. const (
  13. lineChartXAxisName = "Date"
  14. lineChartYAxisName = "Count"
  15. lineChartHeight = 700
  16. lineChartWidth = 1280
  17. colorMultiplier = 256
  18. imgStrPrefix = "data:image/png;base64,"
  19. pieLabelFormat = "%v %v"
  20. barChartTryAgainErr = "invalid data range; cannot be zero"
  21. )
  22. var (
  23. lineChartStyle = chart.Style{
  24. Padding: chart.Box{
  25. Top: 30,
  26. Left: 150,
  27. },
  28. }
  29. defaultChartStyle = chart.Style{
  30. Padding: chart.Box{
  31. Top: 30,
  32. },
  33. }
  34. timeFormat = chart.TimeDateValueFormatter
  35. )
  36. type LineYValue struct {
  37. Name string
  38. Values []float64
  39. }
  40. type ChartValue struct {
  41. Name string
  42. Value float64
  43. }
  44. // createLineChart 创建线性图
  45. func createLineChart(title string, endTime time.Time, values []LineYValue) (img string, err error) {
  46. if len(values) == 0 {
  47. return
  48. }
  49. // 1、计算X轴
  50. lenX := len(values[0].Values)
  51. // X轴内容xValues 及 X轴坐标ticks
  52. var xValues []time.Time
  53. var ticks []chart.Tick
  54. for i := lenX - 1; i >= 0; i-- {
  55. curTime := endTime.AddDate(0, 0, -i)
  56. xValues = append(xValues, curTime)
  57. ticks = append(ticks, chart.Tick{Value: getNsec(curTime), Label: timeFormat(curTime)})
  58. }
  59. // 2、生成Series
  60. var series []chart.Series
  61. for _, yValue := range values {
  62. series = append(series, chart.TimeSeries{
  63. Name: yValue.Name,
  64. Style: chart.Style{
  65. // 随机渲染线条颜色
  66. StrokeColor: drawing.Color{
  67. R: uint8(rand.Intn(colorMultiplier)),
  68. G: uint8(rand.Intn(colorMultiplier)),
  69. B: uint8(rand.Intn(colorMultiplier)),
  70. A: uint8(colorMultiplier - 1), // 透明度
  71. },
  72. },
  73. XValues: xValues,
  74. YValues: yValue.Values,
  75. })
  76. fmt.Println(series)
  77. }
  78. // 3、新建图形
  79. graph := chart.Chart{
  80. Title: title,
  81. Background: lineChartStyle,
  82. Width: lineChartWidth,
  83. Height: lineChartHeight,
  84. XAxis: chart.XAxis{
  85. Name: lineChartXAxisName,
  86. ValueFormatter: timeFormat,
  87. Ticks: ticks,
  88. },
  89. YAxis: chart.YAxis{
  90. Name: lineChartYAxisName,
  91. },
  92. Series: series,
  93. }
  94. graph.Elements = []chart.Renderable{
  95. chart.LegendLeft(&graph),
  96. }
  97. // 4、输出目标
  98. //img, err = writeLineChart(&graph)
  99. img, err = writeLineChartToPng(&graph)
  100. return
  101. }
  102. // getNsec 获取纳秒数
  103. func getNsec(cur time.Time) float64 {
  104. return float64(cur.Unix() * int64(time.Second))
  105. }
  106. func writeLineChartToPng(c *chart.Chart) (img string, err error) {
  107. f, err := os.Create("graph.png")
  108. if err !=nil {
  109. fmt.Println(err.Error())
  110. }
  111. err = c.Render(chart.PNG, f)
  112. return
  113. }
  114. func writeLineChart(c *chart.Chart) (img string, err error) {
  115. var imgContent bytes.Buffer
  116. err = c.Render(chart.PNG, &imgContent)
  117. if err != nil {
  118. return
  119. }
  120. img = imgToStr(imgContent)
  121. return
  122. }
  123. func imgToStr(imgContent bytes.Buffer) string {
  124. return imgStrPrefix + base64.StdEncoding.EncodeToString(imgContent.Bytes())
  125. }
  126. // createPieChart 创建饼图
  127. func createPieChart(title string, pieValues []ChartValue) (img string, err error) {
  128. if len(pieValues) == 0 {
  129. return
  130. }
  131. // 1、构建value
  132. var values []chart.Value
  133. for _, v := range pieValues {
  134. values = append(values, chart.Value{
  135. Value: v.Value,
  136. Label: fmt.Sprintf(pieLabelFormat, getSimpleSensType(v.Name), formatValue(v.Value)),
  137. })
  138. }
  139. // 2、新建饼图
  140. pie := chart.PieChart{
  141. Title: title,
  142. Background: defaultChartStyle,
  143. Values: values,
  144. }
  145. // 4、输出目标
  146. img, err = writePieChart(&pie)
  147. return
  148. }
  149. func formatValue(f float64) string {
  150. return fmt.Sprintf("%.2fW", f/10000)
  151. }
  152. func getSimpleSensType(name string) string {
  153. if name == "个人数据" {
  154. return "Personal"
  155. }
  156. return "Other"
  157. }
  158. func writePieChartToPng(c *chart.PieChart) (img string, err error) {
  159. f, _ := os.Create("pie.png")
  160. err = c.Render(chart.PNG, f)
  161. return
  162. }
  163. func writePieChart(c *chart.PieChart) (img string, err error) {
  164. var imgContent bytes.Buffer
  165. err = c.Render(chart.PNG, &imgContent)
  166. if err != nil {
  167. return
  168. }
  169. img = imgToStr(imgContent)
  170. return
  171. }
  172. // createBarChart 创建柱状图
  173. func createBarChart(title string, barValues []ChartValue) (img string, err error) {
  174. if len(barValues) == 0 {
  175. return
  176. }
  177. // 1、构建value
  178. var values []chart.Value
  179. for _, v := range barValues {
  180. values = append(values, chart.Value{
  181. Value: v.Value,
  182. Label: v.Name,
  183. })
  184. }
  185. // 2、新建饼图
  186. bar := chart.BarChart{
  187. XAxis: chart.Style{
  188. TextWrap: 0, // default 1为可以溢出规定的范围
  189. },
  190. Width: 2560,
  191. BarWidth: 50,
  192. BarSpacing: 300,
  193. Title: title,
  194. Background: defaultChartStyle,
  195. Bars: values,
  196. }
  197. // 4、输出目标
  198. img, err = writeBarChart(&bar)
  199. if err != nil && err.Error() == barChartTryAgainErr {
  200. // 添加一个隐藏条目,设置透明度A为0, 设置任意属性如R不为0即可
  201. values = append(values, chart.Value{
  202. Style: chart.Style{
  203. StrokeColor: drawing.Color{R: 1},
  204. },
  205. Value: 0,
  206. Label: "",
  207. })
  208. bar.Bars = values
  209. img, err = writeBarChart(&bar)
  210. }
  211. return
  212. }
  213. func writeBarChartToPng(c *chart.BarChart) (img string, err error) {
  214. f, _ := os.Create("bar.png")
  215. err = c.Render(chart.PNG, f)
  216. return
  217. }
  218. func writeBarChart(c *chart.BarChart) (img string, err error) {
  219. var imgContent bytes.Buffer
  220. err = c.Render(chart.PNG, &imgContent)
  221. if err != nil {
  222. return
  223. }
  224. img = imgToStr(imgContent)
  225. return
  226. }