MCPcopy Index your code
hub / github.com/gonum/plot / ExampleBarChart_positiveNegative

Function ExampleBarChart_positiveNegative

plotter/barchart_example_test.go:159–249  ·  view source on GitHub ↗

This example shows a bar chart with both positive and negative values.

()

Source from the content-addressed store, hash-verified

157
158// This example shows a bar chart with both positive and negative values.
159func ExampleBarChart_positiveNegative() {
160 rnd := rand.New(rand.NewPCG(1, 1))
161
162 // Create random data points between -1 and 1.
163 const n = 6
164 data1 := make(plotter.Values, n)
165 data2 := make(plotter.Values, n)
166 net := make(plotter.XYs, n) // net = data1 + data2
167 for i := range n {
168 data1[i] = rnd.Float64()*2 - 1
169 data2[i] = rnd.Float64()*2 - 1
170 net[i].X = data1[i] + data2[i]
171 net[i].Y = float64(i)
172 }
173
174 // splitBySign splits an array into two arrays containing the positive and
175 // negative values, respectively, from the original array.
176 splitBySign := func(d plotter.Values) (pos, neg plotter.Values) {
177 pos = make(plotter.Values, len(d))
178 neg = make(plotter.Values, len(d))
179 for i, v := range d {
180 if v > 0 {
181 pos[i] = v
182 } else {
183 neg[i] = v
184 }
185 }
186 return
187 }
188
189 data1Pos, data1Neg := splitBySign(data1)
190 data2Pos, data2Neg := splitBySign(data2)
191
192 const barWidth = 0.3 * vg.Centimeter
193 pos1, err := plotter.NewBarChart(data1Pos, barWidth)
194 if err != nil {
195 log.Panic(err)
196 }
197 pos2, err := plotter.NewBarChart(data2Pos, barWidth)
198 if err != nil {
199 log.Panic(err)
200 }
201 neg1, err := plotter.NewBarChart(data1Neg, barWidth)
202 if err != nil {
203 log.Panic(err)
204 }
205 neg2, err := plotter.NewBarChart(data2Neg, barWidth)
206 if err != nil {
207 log.Panic(err)
208 }
209
210 netDots, err := plotter.NewScatter(net)
211 if err != nil {
212 log.Panic(err)
213 }
214 netDots.Radius = vg.Points(1.25)
215
216 pos2.StackOn(pos1) // Specify that pos2 goes on top of pos1.

Callers

nothing calls this directly

Calls 9

StackOnMethod · 0.95
NewBarChartFunction · 0.92
NewScatterFunction · 0.92
PointsFunction · 0.92
NewLineFunction · 0.92
NewFunction · 0.92
NominalYMethod · 0.80
SaveMethod · 0.80
AddMethod · 0.45

Tested by

no test coverage detected