preface
As a front-end typist, the only thing I hate more than anyone else are charts: one makes me sad, one makes me sad; More annoying than this is the document written unclear chart library (large probability is nine years of compulsory education did not learn Chinese), let me love and hate! Therefore, this blog post will be boring, and it will simply describe the process of using BizCharts. Of course, the important thing is to summarize the pits encountered (follow the principle of no two pits, no two bubbles for a girl).
By the way, speaking of BizCharts, let’s thank Alibaba for open-source use of this handy (if occasionally not so handy, but occasionally quite often) React chart library, which is a boon for front-end typists using the React stack. This article will not have too much API explanation, the specific interface can see the official website documentation of death pass.
Proper length
At the beginning, the visual designer coaxed me and said: “my requirements are not high, as GOOD as I used to be”, ah bah, said wrong, “my requirements are: as long as the data can be displayed with histogram”, so easy
// Import related components
import { Chart, Axis, Tooltip, Geom } from 'bizcharts';
// Mock the data
const str = ['we'.'are'.'the'.'black'.'gold'.'team'];
const mockData = (a)= > {
let result = [];
for (let i = 0, len = 6; i < len; i++) {
result.push({
xAxis: ticks[i],
yAxis: Math.floor(Math.random() * 100)}); }return result;
};
// Chart component
<Chart
width={ 600 }
height={ 400 }
data={ mockData() }
>
{/* * x axis, horizontal axis, data data xAxis attribute value as the column value */}
<Axis name="xAxis"/ > {/* Y axis, vertical axis, data data yAxis attribute value as the column value */}
<Axis name="yAxis"/ > {/* The mouse hover histogram column when the tooltip displays the value */}
<Tooltip />
{/* Geometric marker object, mainly used to describe what graph you want to draw (histogram, line chart, pie chart, area chart) : interval is histogram */}
<Geom
type="interval"
position="xAxis*yAxis"
/>
</Chart>
Copy the code
A wave of operation fierce as a dog, let the visual designer see the effect:
Note: Each column of the histogram is a single point, that is, it reflects the data situation of a certain abscissa. Add that we need a continuous interval column, so the value of the data field as xAxis should be an array containing two elements, indicating the starting value of the interval.
const mockData = (a)= > {
let result = [];
for (let i = 0, len = 6; i < len; i++) {
result.push({
xAxis: [i + 0.01, i + 1 - 0.01].// If you do not add or subtract 0.01, then the end of the first pillar is the same as the beginning of the second pillar, and the two pillars will feel stuck together
yAxis: Math.floor(Math.random() * 100)}); }return result;
};
Copy the code
Visual designer: “Emmmmmm, will the length and width of the chart be a little stiff? The height can be written dead, but the width must be adaptive?”
“MAO Stuffy platform”
<Chart
height={ 400 }
data={ mockData() }
forceFit // As my mother said, adding this attribute can make the graph width adaptive
>
</Chart>
Copy the code
The effect shows a wave
Vision (honey smile) : “Ape, you have a bug in this thing.”
“Nonsense, you stupid * don’t know how to use it.”
“Ahhhhhh, the window does adapt when you enlarge it, but when you shrink it, it dies.”
(flattering) “Damn, just give me two more minutes to turn the bug into ice…”
Note: The Chart component’s Father has a flex layout, and the Father uses flex adaptive width. So, if you have multiple charts stacked side by side, don’t use flex layout, set the width of the Father component to a percentage, and then forceFit will work. Meanwhile, BizCharts has a shake proof for redrawing, which only happens when scaling is stopped.
“Over, take it.”
(a look of disdain) “Wow ~ good good, dare me to adjust a little detail, I promise just a little bit!”
“Come on baby!”
“
- Hover pillar mouse, why there is a very ugly box behind the pillar, change the color bar!
- Hover pillar: Tooltip style is ugly, I will design one for you later
- Mouse hover column, column color should be changed, more user friendly!!
- . Hey, don’t take the knife
“
After the vision is killed, the need is still to do, first solve the victim’s first last wish.
The Tooltip component provides an attribute, Crosshairs, that sets the Tooltip’s helper wire and helper box; By default, this property enables vertical guides for Geom components of type ‘line’, ‘area’, ‘path’, and ‘areaStack’, and displays rectangular background boxes for Geom components of type ‘interval’. This is the box the victim said was ugly!
<Tooltip crosshairs={ false} / >Copy the code
Ok, get rid of the box! Gee, didn’t we say we were going to change the color? Ok, change it
<Tooltip
crosshairs={{
type: "rect" // Optional values: RECt, X, y, cross, corresponding to the auxiliary, parallel X-axis auxiliary line, parallel Y-axis auxiliary line, cross auxiliary line respectively
style: {
fill: 'red'.// Secondary box color
shadowColor: 'red'.// The color of the shadow around the helper box
shadowBlur: 1.// The opacity of the shadow around the auxiliary box
opacity: 0 // The transparency of the auxiliary box
}
}}
/>
Copy the code
Note: If the helper line is turned on, i.e. type is not “rect”, then the above style definition will not work. The reason is that after looking at the source code for this component, it turns out that the attribute that describes the style of the guides is not a Style object, but a lineStyle object, which is not stated in the official documentation.
<Tooltip
crosshairs={{
type: "y"
lineStyle: {
stroke: 'red'.// Auxiliary line color
lineWidth: 4.// The auxiliary line width is px
opacity: 1 // Auxiliary line transparency
}
}}
/>
Copy the code
Seems like it was easy enough to fulfill the victim’s first wish, isn’t it a little cruel to kill sight like that? This is what happened. Let’s carry on with his wishes.
My second wish was to change the style of the tooltip. Now that you’re styling toolTip, you should continue with the ToolTip component. Reading through the document, it also has an itemTpl attribute, which is the template from which the Tooltip can be defined
// Define a template
// name-value is the key-value of the related column
const tooltipsDisplayTpl = ` {name} {value}
`;
G2-tooltip {background-color: rgba(44, 49, 68, 0.80)! important; } .chart-tooptip { margin: 0; color: white; } .chart-tooptip-right { margin-right: 12px; } * /
<Tooltip
crosshairs={ false }
itemTpl={ tooltipsDisplayTpl }
showTitle={ false } // The title (the scale corresponding to the horizontal axis) usually affects my appearance level, not my body, but my face, so I don't want to face
/>
Copy the code
Note: If you want to customize the tooltip display, you also need to set the Geom component’s ToolTip property, which maps the data to the Tooltip object. So if this property value is false, no data is passed to the Tooltip component (the Tooltip only displays title); It can also be set to a string to display the corresponding data fields of the string. But, it’s not the point
// Define the format of the data returned. The name attribute corresponds to the variable with the same name in itemTpl
const getTooltipData = (xAxis, yAxis) = > {
return {
name: xAxis,
value: yAxis
};
}
<Geom
type="interval"
position="xAxis*yAxis"
tooltip={["xAxis*yAxis", getTooltipData]}
/>
Copy the code
The second wish has come true, and the guilt is a little bit more! Most of all, I always feel like someone is standing behind me and staring at me when I’m writing code.
Maybe realize all will not have this feeling, then continue the third will: “change the mouse hover column when the column color”, through the entire document, found no interface on hover ah! Looks like vision is dying in his grave. Amen.
Just as I felt a growing chill in my back, I noticed that the Geom component had a property active
The document actually describes it in two sentences, and there are no examples. I can only try a wave, set to true, well, hover column color change!!
<Geom
type="interval"
position="xAxis*yAxis"
tooltip={["xAxis*yAxis", getTooltipData]}
active={ true} / >Copy the code
What if you need to customize the mouse hover column style? I tried again against the SELECT attribute of the Geom document
<Geom
type="interval"
position="xAxis*yAxis"
tooltip={["xAxis*yAxis", getTooltipData]}
style={{ cursor: 'pointer' }} // When the mouse hover goes up, display small hands, free to send
active={[
true,
{
style: {
fill: 'black'.// The color of the column, continue to mourn
shadowColor: 'red'.// Overall shadow color, including edges
shadowBlur: 1.// The opacity of the shadow
opacity: 0 // Column color transparency}}]} / >Copy the code
“Don’t die, dog. I got it.”
“Fuck, I’ve been faking my death for two days, do you dare slow down a little bit?”
“The official document had just one line: ‘To be understood but not spoken! I have limited talent. I’ve been thinking for a long time.”
“Oh, look! There’s a bug again! Your watch is flashing.”
(shakes him by the neck) “That’s not a fucking bug!!”
On the other hand, when data is updated, switching from old data to new data can be very abrupt, without buffering, and very uncomfortable to watch. I thought, when the data update, add an animation bai! However, if the original animation works, the updated animation does not work. Because I was in a hurry to get off work, I decided to use a DataSet: a DataSet that manages tabbed data and reportedly animates me when updating data (it can easily import non-JSON data, etc.). Here are some examples that I haven’t studied in detail, so I’ll share them later. No good reason, in short, so sharp!
/ / installation
// npm install @antv/data-set
/ / introduction
import DataSet from '@antv/data-set';
// Generate a View instance as a class property, so do not generate this instance in the render method
dv = new DataSet().createView();
render() {
this.dv.source(data);
<Chart
height={ 400 }
data={ this.dv }
forceFit
></Chart>
}
Copy the code
“Ape, 6 o! Do you want a late snack? My”
“I’m not hungry, but if you invite me, go.”
After eating a bucket of instant noodles……
“Look, ape, you’ve had your midnight snack too…”
“What are you doing now…?”
It is simply full of food and lust!!
“I just thought the color of the column could be tweaked to make our products look better.”
“Dog, will you take a beating? “
(pitiful) “after beating can add a gradual change…… “
“…… “
“I know you are the best to me, I will give you back pinch thigh ~”
“Get out of here.”
<Geom
type="interval"
position="xAxis*yAxis"
tooltip={["xAxis*yAxis", getTooltipData]}
color={['xAxis'.'#3DA4FF-#FFFFFF']} / >Copy the code
“I want a gradient from top to bottom, not left to right.”
“Don’t… Don’t… Device… I… To change… Change…”
<Geom
type="interval"
position="xAxis*yAxis"
tooltip={["xAxis*yAxis", getTooltipData]}
color={['xAxis'.'l(90) 0:#3DA4FF 1:#FFFFFF']} / >Copy the code
Note: l is refers to the linear gradient, 90 refers to rotate ninety degrees (i.e. the gradient from top to bottom, the reader can try a few more positions, ah bah, try a few more angles) color value indicates the initial color of 0 s and 1 s calibration values and termination, note that the color value can not use a color name, such as “red”, “blue” and so on You can add more gradient values, such as
color="L (90) : 0 # 000000 0.5: # FFFFFF 1: # 000000"
Copy the code
Note: If Geom is of area type, the first gradient method does not work and the second gradient method must be used
“Dog, I really have to get off work.”
“Well, look at the gradients, let’s do a wave of color sorting.”
“No talking, Goodbye! “
“Eat my night snack.”
“You are a lung, and want to use instant noodles to fool me!! “
“Masturbating, lying to you I’m a dog.”
“Emmmmmm… “
Dv. transform has some basic functions built into it: filter, map, pick, rename, reverse… You can check the documentation for details
Simply add the groupBy field and add the corresponding classify field to the incoming raw data.
dv.transform({
groupBy: ['classify'].// Group with classify
});
Copy the code
“Ape, you have to customize the color.”
(etc)
<Geom
position={'xAxis*yAxis'}
color={['classify', classify => {
// Return different colors for different fields
return classify === 'test' ? 'red' : 'yellow';
}]}
style={{ cursor: 'pointer'}} / >Copy the code
As a responsible front end typist, even if the design does not require it, I still need to clarify that the scale values on the horizontal axis are customizable
<Axis
name={xAxis}
label={{
textStyle: {
fill: 'red'./ / color
textBaseline: 'top' // Align the baseline
},
formatter: (val) = > {
return `${ val }\n Newline '
}
}}
/>
Copy the code
“Dog, masturbate!! “
“Or eat a instant noodles ???? “
Dog, pawn!
conclusion
Thank you for reading my nonsense. One thing that needs to be corrected is that our programmers have a very friendly relationship with visual and interaction designers. The above summary, only reference learning, do not like spray; If there is any mistake, welcome to correct.
@Author: beidan, PaperCrane