HorizontalBar Chart-III
In the last chapter we made horizontal Bar charts with 3-data points and colors. Today we will look at how to export data and build chart.
We have a data set which is in the file alphabets.csv it is the list of frequency of alphabets in english language from 40,000 samples .We will read the csv file with d3 csv and will follow the same pattern as we did before. xAxis will be the frequency chart and yAxis will be the letters.
const fruits=
[
{ name: "🍊", count: 21 },
{ name: "🍇", count: 13 },
{ name: "🍏", count: 8 },
{ name: "🍌", count: 5 },
{ name: "🍐", count: 3 },
{ name: "🍋", count: 2 },
{ name: "🍎", count: 1 },
{ name: "🍉", count: 1 }
] The above dataset is what I started with. Since I am using react so I have made horizontal bar chart components that takes the data which is in the above format. So after importing data I will have to convert the data into above format using the d3 csv tool.
d3.csv(location,formating function)
.then(doSomething)The above code needs to be inside the react useEffect hook so that it doesn't keep on calling the data.
useEffect(() => {
const format =
({ letter, frequency }) => ({
name: letter,
value: +frequency
})
csv('/alphabet.csv', format).then(value => {
value.sort(
(a, b) => descending(a.count, b.count)
)
setData(value)})
}, [])The format function is used to process the data to be similar to fruits. Then I am using d3's descending function to arrange the data in descending order.
Loading.....
There is one tricks used here to make the data look nice. The frequency data has been formatted to percentage for better readability.
d3.format('.0%)(.0819)The graph can be formatted better and the percentage adjusted for the 0%. But since I am using a common component so I will leave those for next time.