*ฅ^•ﻌ•^ฅ* ✨✨  HWisnu's blog  ✨✨ о ฅ^•ﻌ•^ฅ

Dataviz libraries in Python and Javascript

Introduction

One of my primary programming projects involves building a tool to facilitate analysis of the stock market and make informed investment decisions on which stocks to purchase.

Data Visualization in Python

In the finance world, working with large amounts of data is common, and visualizing this data is essential for comprehension. To achieve this, I initially relied on Python for data analysis and visualization. There are several decent data visualization libraries in Python that I have utilized, including Bokeh, Plotly, Altair, and hvPlot, which supports multiple backend engines such as Bokeh, Plotly, and Matplotlib.

However, I only use interactive data visualization libraries, as static libraries like Matplotlib and Seaborn are unsuitable for my use case. The inability to interact with the chart and retrieve specific data information is a major limitation.

Although there may be other Python data visualization libraries that I haven't explored, the purpose of this post is to highlight the ease of integrating data visualization libraries from JavaScript into Python applications. If I were to rate Python data visualization libraries, I would give them a score of 6 or 7 out of 10, indicating that they are decent but not exceptional.

Data Visualization in Javascript

In contrast, I would rate JavaScript data visualization libraries a score of 9 out of 10, as they are significantly better. For instance, PlotlyJS is far superior to the pure Python version of Plotly.

I invested three months of my time learning JavaScript, which proved to be a worthwhile investment. I can now utilize any JavaScript data visualization library, and I would encourage Python developers who work extensively with data and visualization to learn JavaScript as well: it is almost as easy as Python! (even though JS gotchas are kinda disgusting LOL!)

Javascript Gotchas

Try running these JS gotchas:

'2' + '2' - '2'

--> result = 20

[6, -2, 2, -7].sort()

--> result = [-2, -7, 2, 6]

Aren't you disgusted already?? Well I am! But no, those are just to make fun of JS...the dataviz libraries are awesome!

Workflow for Using JavaScript Data Visualization Libraries

The workflow for using JavaScript dataviz libraries is not significantly different from that of Python. Typically, I prepare the necessary data in Python and then feed it into JavaScript. The example code below illustrates the final stage of backend data preparation for a tool I built to track shareholder movement:

sh_dict = {}
for col in top10_sh.columns:
    sh_dict[col] = top10_sh[col]

data = []
for col, num in sh_dict.items():
    series = {
        "name": col,
        "data": round(num, 2).values.tolist()
    }
    data.append(series)

df_time = pd.DataFrame(num.index.tolist(), columns=["Period"])
df_time["Period"] = pd.to_datetime(df_time["Period"], format='%Y-%m-%d')
categories = (df_time["Period"].dt.strftime('%b\'%y')).tolist()

xaxis = {
    "categories": categories
}

series["data"]

final_data = {
    "series": data,
    "xaxis": xaxis,
}

series_sh = data
xaxis_sh = xaxis

Sending Data to Frontend HTML

After preparing the data, I send it to the frontend HTML:

<script>
    const stock = {{ stock | tojson }};
    const series_sh = ({{ series_sh | tojson }});
    const xaxis_sh = ({{ xaxis_sh | tojson }});
</script>

Capturing Data in JavaScript File

Then, I capture the data in my JavaScript file and process the visualization:

const stock_Q = stock;
const series_Q = series_sh;
const xaxis_Q = xaxis_sh;

var options1 = {
    series: series_Q,
    chart: {
      type: 'line',
      id: 'line-1',
      group: 'shareholder',
      height: 400,
      toolbar: {
        show: false
      },
    },
    colors: ['#ff2c19', '#9CA986', '#F9B572', '#FD8A8A',
            '#A267AC', '#385e4b', '#B9F3FC', '#64CCC5', 
            '#FFF2CC', '#2f6690'
    ],
    theme: {
      mode: 'dark'
    },
    tooltip: {
      y: {
        formatter: function(val) {
          return val.toFixed(2) + "%";
        }
      },
      x: {
        show: true,
      }
    },
    dataLabels: {
      enabled: false
    },
    title: {
      text: `${stock_Q} - Shareholder Movement`,
      align: 'center',
      style: {
        fontSize: '18px',
        fontWeight: 'bold',
        color: '#fff'
      },
      subtitle: {
        text: 'Data from 2016 to 2023',
        align: 'center',
        style: {
          fontSize: '14px',
          color: '#666'
        }
      }
    },
    xaxis: xaxis_Q,
    yaxis: {
        opposite: false,
        logarithmic: false,
        logBase: 3,
        labels: {
          minWidth: 40
        }
    },
    legend: {
      show: false,
      /* fontSize: '10px' */
    },
};

var chart1 = new ApexCharts(document.querySelector("#chart_shRoster"), options1);
chart1.render();

Benefits of Using JavaScript Data Visualization Libraries

The best part: the same workflow is applicable to all JS dataviz libs, here are the ones I have been using:

In addition to the ease of integration, there are several other benefits to using JavaScript data visualization libraries:

  1. Unlike Python, where we need to use pip to install libraries, JavaScript data visualization libraries can be easily imported via a Content Delivery Network (CDN), eliminating the need for manual installation.
  2. JavaScript data visualization libraries are often significantly faster and more performant than their Python counterparts.

Conclusion

I would like to reiterate my message: if you work extensively with data and visualization, I strongly believe that learning JavaScript is worth the investment, simply to gain access to the excellent data visualization libraries available in the JavaScript ecosystem.

#data #dataviz #javascript #python #visualization