Yoctol / react-d3-cloud

A word cloud react component built with d3-cloud.
https://yoctol.github.io/react-d3-cloud
MIT License
142 stars 47 forks source link

Improved fontSizeMapper function #116

Closed denishrana09 closed 5 years ago

denishrana09 commented 5 years ago

As I couldn't find any optimized fontSizeMapper function, I have created one,

const getRelativeValue = (value, max, totalHashtags) => {
  let percentage = 100 - Math.abs((max - value) / max) * 100;
  let maxFontSize;
  if (totalHashtags > 60) {
    maxFontSize = 50;
  } else {
    maxFontSize = 70;
  }
  const minFontSize = 12;
  const fontSizeDiff = maxFontSize - minFontSize;
  const relativeFontSize = 12 + Math.floor((fontSizeDiff * percentage) / 100);
  return relativeFontSize;
};

here, getHashtagData function will assign your word a fontSize directly to it's value attribute by the help of getRelativeValue function. I count every word's relative value, if word has minimum value then fontSize 12 will be assigned, and same for max value.

The condition (totalHashtags > 60) is added because if you get so many of words and if WordCloud coudn't able to feet in the area then I changed the maxFontSize to 50.

const getHashtagData = data => {
  let d = [];
  if (data) {
    let max = 0;
    data.forEach(item => {
      // based on whatever structure you have in data
      if (item.count1 + item.count2 > max) {
        max = item.count1 + item.count2;
      }
    });
    data.forEach(item =>
      d.push({
        text: item.text,
        value: getRelativeValue(
          item.count1 + item.count2,
          max,
          data.length,
        ),
      }),
    );
  }
  return d;
};
const fontSizeMapper = (word) => {
  return word.value;
};
<WordCloud
        data={getHashtagData(hashtagArray)}
        fontSizeMapper={fontSizeMapper}
        onWordClick={onWordClick}
        height={250}
        width={this.props.width}
  />

Hope you liked the simple but useful logic.