有許多JavaScript 庫可用于繪制不同的圖表,包括折線圖、條形圖、圖形等等。
如果您正在嘗試學(xué)習(xí)如何使用 JavaScript 在您的網(wǎng)站上動態(tài)顯示數(shù)據(jù),Chart.js是您可以測試的庫之一。
React是最好的 JavaScript 框架之一,還提供了一組很酷的圖表庫,您可以通過這些庫創(chuàng)建 Web 和混合應(yīng)用程序的酷界面。
開始使用 Chart.js 開發(fā)數(shù)據(jù)可視化的步驟是什么?
在本文中了解如何操作。
Chart.js 是一個開源的數(shù)據(jù)可視化 JavaScript 庫,可以繪制基于 HTML 的圖表。
它目前能夠支持八種可以動畫的交互式圖表。要使用 chart.js 創(chuàng)建基于 HTML 的圖表,您需要一個HTML 畫布來顯示它。
該庫可用于一系列數(shù)據(jù)集和其他自定義參數(shù),如邊框顏色、背景顏色等。
其中之一的數(shù)據(jù)集稱為標(biāo)簽數(shù)據(jù)集,即 X 軸的值。另一個是數(shù)字的集合,通常沿著 Y 軸。
還需要在圖表對象內(nèi)部定義圖形類型,以確保庫可以確定要繪制什么圖形。
正如我們之前提到的,您可以使用 chart.js 制作各種圖表。
在本教程中,我們將從條形圖和折線圖開始。一旦您了解了這些圖表類型的概念,您將擁有繪制其他可用圖表所需的信息和工具。
首先使用 chart.js,創(chuàng)建所需的文件。在本指南中,文件的名稱將是 chart.html、plot.js 和 index.css。您可以使用任何命名約定來命名您的文件。
然后,將以下代碼復(fù)制并粘貼到 HTML 文檔的標(biāo)題區(qū)域。這將創(chuàng)建提供指向 Chart.js 內(nèi)容交付網(wǎng)絡(luò) ( CDN ) 的鏈接。
在 chart.html 上:
<head> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"> </script> </head>
創(chuàng)建HTML畫布以顯示圖表。為您的圖表提供其 ID。此外,連接位于 head 部分的 CSS (index.css) 文檔并鏈接到 body 部分的 JavaScript (plot.js) 文件。
HTML文件的格式如下:
<!DOCTYPE HTML><html> <head> <title> Chart </title> <link rel="stylesheet" href="index.css"> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.8.0/Chart.min.js"></script> </head> <body> <header> <h1> Charts </h1> </header> <canvas id="plots" style="width:100%;max-width:700px"></canvas><script src="plot.js"></script></body></htm/>
在你的 CSS 中:
body{ background-color:#383735;}h1{ color:#e9f0e9; margin-left:43%;}#plots{ margin:auto; background-color: #2e2d2d;}
上面顯示的CSS樣式不是標(biāo)準(zhǔn)的。你可以根據(jù)你的喜好,根據(jù)你的 DOM 的結(jié)構(gòu)來設(shè)置它的樣式。當(dāng)您完成 HTML 或 CSS 文件并準(zhǔn)備好使用 JavaScript 創(chuàng)建圖表時。
對于要使用 chart.js 創(chuàng)建的折線圖,您需要將圖表類型更改為折線。這告訴庫如何繪制折線圖。
為了顯示這一點,在 JavaScript 文件中:
// Get the HTML canvas by its id plots = document.getElementById("plots");<strong>// Example datasets for X and Y-axesstrong> var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul"]; <strong>//Stays on the X-axisstrong> var traffic = [65, 59, 80, 81, 56, 55, 60] //Stays on the Y-axis // Create an instance of Chart object:new Chart(plots, { type: 'line', <strong>//Declare the chart typestrong> data: { labels: months, <strong>//X-axis datastrong> datasets: [{ data: traffic, <strong>//Y-axis datastrong> backgroundColor: '#5e440f', borderColor: 'white', fill: false, //Fills the curve under the line with the background color. It's true by default }] },});
輸出:
隨意將您的填充值更改為真實,使用其他數(shù)據(jù)或修改顏色以觀察發(fā)生的情況。
如您所見,頂部附近有一個額外的圖例框。您可以將其從選項參數(shù)中取出。
除了刪除或添加圖例之外,它的選項參數(shù)還可用于進(jìn)行其他調(diào)整。例如,您可以應(yīng)用它來使軸從零開始。
定義選項參數(shù)。這是 JavaScript 文件中圖表部分的外觀:
// Create an instance of Chart object:new Chart(plots, { type: 'line', <strong>//Declare the chart typestrong> data: { labels: months, <strong>//X-axis datastrong> datasets: [{ data: traffic, <strong>//Y-axis datastrong> backgroundColor: '#5e440f', <strong>//Color of the dotsstrong> borderColor: 'white', <strong>//Line colorstrong> fill: false, //Fills the curve under the line with the background color. It's true by default }] },<strong> //Specify custom options:strong> options:{ legend: {display: false}, //Remove the legend box by setting it to false. It's true by default. //Specify settings for the scales. To make the Y-axis start from zero, for instance: scales:{ yAxes: [{ticks: {min: 0}}] //You can repeat the same for X-axis if it contains integers. } } });
輸出:
您還可以為每個點的背景選擇不同的顏色。然而,這種方式的背景顏色變化通常更適合條形圖。
這是唯一一次您必須將圖表類型更改為條形。無需更改顏色選項的選項,因為條形將自動繼承其背景顏色:
// Create an instance of Chart object:new Chart(plots, { type: 'bar', <strong>//Declare the chart typestrong> data: { labels: months, <strong>//X-axis datastrong> datasets: [{ data: traffic, <strong>//Y-axis datastrong> backgroundColor: '#3bf70c', <strong>//Color of the barsstrong> }] }, options:{ legend: {display: false}, //Remove the legend box by setting it to false. It's true by default. }});
輸出:
隨意將 Y 軸設(shè)置為從零或任何其他值開始,就像您對折線圖所做的那樣。
要為每個條使用不同的顏色,您必須將與數(shù)據(jù)中的項目數(shù)量兼容的顏色數(shù)組傳遞給 backgroundColor 參數(shù):
// Create an instance of Chart object:new Chart(plots, { type: 'bar', <strong>//Declare the chart typestrong> data: { labels: months, <strong>//X-axis datastrong> datasets: [{ data: traffic, <strong>//Y-axis datastrong> <strong>//Color of each barstrong>: backgroundColor: [ "rgba(196, 190, 183)", "rgba(21, 227, 235)", "rgba(7, 150, 245)", "rgba(240, 5, 252)", "rgba(252, 5, 79)", "rgb(0,12,255)", "rgb(17, 252, 5)"], }] }, options:{ legend: {display: false}, //Remove the legend box by setting it to false. It's true by default. }});
輸出:
要創(chuàng)建餅圖,請將圖表類型切換為餅圖。也可以使圖例的顯示為真以確定餅圖的每個部分是什么:
// Create an instance of Chart object:new Chart(plots, { type: 'pie', //Declare the chart type data: { labels: months, //Defines each segment datasets: [{ data: traffic, //Determines segment size //Color of each segment backgroundColor: [ "rgba(196, 190, 183)", "rgba(21, 227, 235)", "rgba(7, 150, 245)", "rgba(240, 5, 252)", "rgba(252, 5, 79)", "rgb(0,12,255)", "rgb(17, 252, 5)"], }] }, options:{ legend: {display: true}, //This is true by default. } });
輸出:
就像您在前面的示例中所做的那樣,通過更改圖表類型來嘗試不同的圖表。
但是,支持一些 chart.js 圖表類型。chart.js 圖表類型,您可以使用上面的代碼約定:
盡管您在本教程中只熟悉了餅圖、折線圖和條形圖,但使用 chart.js 繪制其他圖表的 Code Pattern 也基于相同的原理。您也可以自由地嘗試其他圖表。
沒發(fā)現(xiàn) ECharts 這款神器的時候,之前所做的數(shù)據(jù)統(tǒng)計圖只能自個純手寫,倒也是可以實現(xiàn),只不過特別的費時。后來無意中在網(wǎng)上瞄到 ECharts 這款專門用來生成數(shù)據(jù)圖表的插件,便嘗試了一下,那感覺真的不要太爽!
官方介紹
ECharts,一個使用 JavaScript 實現(xiàn)的開源可視化庫,可以流暢的運行在 PC 和移動設(shè)備上,兼容當(dāng)前絕大部分瀏覽器,底層依賴輕量級的矢量圖形庫 ZRender,提供直觀,交互豐富,可高度個性化定制的數(shù)據(jù)可視化圖表。
獲取 ECharts
1、下載地址
https://github.com/apache/incubator-echarts
2、點擊紅色箭頭按鈕,將壓縮包下載下來
image
3、echarts 庫放在解壓后文件夾中的 dist 目錄里
image
將整個 dist 目錄復(fù)制到你的項目中去,可重命名為 echarts
備注:若不想下載 ECharts 庫文件,可在頭部直接引用 bootcdn 上的 echarts 文件,地址為:
https://cdn.bootcss.com/echarts/4.2.1-rc1/echarts.min.js
繪制數(shù)據(jù)圖表
1、柱狀圖
柱狀圖效果預(yù)覽
代碼實現(xiàn)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>數(shù)據(jù)統(tǒng)計圖:柱狀圖</title> <!-- 引入 ECharts 文件 這里選擇min.js壓縮版的echarts --> <script src="echarts/echarts.min.js"></script> </head> <body> <!-- 為ECharts準(zhǔn)備一個具備大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基于準(zhǔn)備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項和數(shù)據(jù) var option = { title: { text: '2014-2019年 前端人均工資' }, tooltip: {},//提示框組件(鼠標(biāo)移動到數(shù)字表時觸發(fā)) xAxis: { //x軸 data: ["2014年","2015年","2016年","2017年","2018年","2019年"] }, yAxis: {},//y軸 內(nèi)容會自動從以下的series.data 中獲取 series: [{ name: '人均工資', type: 'bar', //類型為:柱狀圖 data: [3800, 4600, 5100, 5800, 6300, 7300] //x軸項目對應(yīng)的數(shù)據(jù) }] }; // 使用剛指定的配置項和數(shù)據(jù)顯示圖表。 myChart.setOption(option); </script> </body> </html>
2、折線圖
折線圖效果預(yù)覽
代碼實現(xiàn)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>數(shù)據(jù)統(tǒng)計圖:折線圖</title> <!-- 引入 ECharts 文件 這里選擇min.js壓縮版的echarts --> <script src="echarts/echarts.min.js"></script> </head> <body> <!-- 為ECharts準(zhǔn)備一個具備大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基于準(zhǔn)備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項和數(shù)據(jù) var option = { title: { text: '未來一周氣溫變化' }, tooltip: { trigger: 'axis' }, xAxis: { type: 'category', data: ['周一','周二','周三','周四','周五','周六','周日'] }, yAxis: { type: 'value', axisLabel: { //坐標(biāo)軸刻度標(biāo)簽的相關(guān)設(shè)置。 formatter: '{value} °C' // 使用字符串模板,模板變量為刻度默認(rèn)標(biāo)簽 {value} } }, series: [ { name:'最高氣溫', type:'line', data:[11, 11, 15, 13, 12, 13, 10], }, { name:'最低氣溫', type:'line', data:[1, -2, 2, 5, 3, 2, 0], } ] }; // 使用剛指定的配置項和數(shù)據(jù)顯示圖表。 myChart.setOption(option); </script> </body> </html>
3、餅圖
餅圖效果預(yù)覽
代碼實現(xiàn)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>數(shù)據(jù)統(tǒng)計圖:餅圖</title> <!-- 引入 ECharts 文件 這里選擇min.js壓縮版的echarts --> <script src="echarts/echarts.min.js"></script> </head> <body> <!-- 為ECharts準(zhǔn)備一個具備大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基于準(zhǔn)備好的dom,初始化echarts實例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項和數(shù)據(jù) var option = { title : { text: '某公司年齡階段的員工占比', x:'center'//水平居中 }, tooltip : {//提示框組件。 trigger: 'item', //'item' 數(shù)據(jù)項圖形觸發(fā),主要在散點圖,餅圖等無類目軸的圖表中使用。 formatter: "{a} <br/>{b} : {c} (rptfxpn%)" //{a}(系列名稱),{b}(數(shù)據(jù)項名稱),{c}(數(shù)值), vbvhjhz(百分比) }, series : [ { name: '年齡占比', type: 'pie', radius : '55%',//餅圖的半徑 center: ['50%', '60%'],//餅圖的中心(圓心)坐標(biāo),數(shù)組的第一項是橫坐標(biāo),第二項是縱坐標(biāo)。 data:[ {value:80, name:'20-25歲'}, {value:30, name:'26-30歲'}, {value:20, name:'31-35歲'}, {value:8, name:'36-40歲'}, {value:5, name:'41歲以上'} ], itemStyle: {//圖形樣式。 emphasis: { shadowBlur: 10, shadowOffsetX: 0, shadowColor: 'rgba(0, 0, 0, 0.5)' } } } ] }; // 使用剛指定的配置項和數(shù)據(jù)顯示圖表。 myChart.setOption(option); </script> </body> </html>
結(jié)語
以上繪制的圖表是數(shù)據(jù)圖中用的頻率較高的三種。不僅如此,ECharts 還可用于地理數(shù)據(jù)可視化的地圖,用于關(guān)系數(shù)據(jù)可視化的關(guān)系圖,多維數(shù)據(jù)可視化的平行坐標(biāo),還有用于 BI 的漏斗圖,并且支持圖與圖之間的混搭。更多有關(guān) ECharts 的使用方法,可參考 ECharts 的官方文檔:
https://echarts.baidu.com/index.html
者: 俊欣
來源:關(guān)于數(shù)據(jù)分析與可視化
今天小編來為大家安利另外一個用于繪制可視化圖表的Python框架,名叫Dash,建立在Flask、Plotly.js以及React.js的基礎(chǔ)之上,在創(chuàng)建之出的目的是為了幫助前端知識匱乏的數(shù)據(jù)分析人員,以純Python編程的方式快速制作出交互特性強(qiáng)的數(shù)據(jù)可視化大屏,在經(jīng)過多年的迭代發(fā)展,如今不僅僅可以用來開發(fā)在線數(shù)據(jù)可視化作品,即便是輕量級的數(shù)據(jù)儀表盤、BI應(yīng)用甚至是博客或者是常規(guī)的網(wǎng)站都隨處可見Dash框架的影子,今天小編就先來介紹一下該框架的一些基礎(chǔ)知識,并且來制作一個簡單的數(shù)據(jù)可視化大屏。
我們先來了解一下Dash框架中的兩個基本概念
Layout顧名思義就是用來設(shè)計可視化大屏的外觀和布局,添加一些例如下拉框、單選框、復(fù)選框、輸入框、文本框、滑動條等組件,其中Dash框架對HTML標(biāo)簽也進(jìn)行了進(jìn)一步的封裝,使得我們直接可以通過Python代碼來生成和設(shè)計每一個網(wǎng)頁所需要的元素,例如
<div>
<h1>Hello World!!</h1>
<div>
<p>Dash converts Python classes into HTML</p>
</div>
</div>
我們轉(zhuǎn)化成Dash的Python結(jié)構(gòu)就是
html.Div([
html.H1('Hello Dash'),
html.Div([
html.P('Dash converts Python classes into HTML'),
])
])
Callbacks也就是回調(diào)函數(shù),基本上是以裝飾器的形式來體現(xiàn)的,實現(xiàn)前后端異步通信的交互,例如我們在點擊按鈕或者下拉框之后出現(xiàn)的功能就是通過回調(diào)函數(shù)來實現(xiàn)的。
在導(dǎo)入模塊之前,我們先用pip命令來進(jìn)行安裝,
! pip install dash
! pip install dash-html-components
! pip install dash-core-components
! pip install plotly
然后我們導(dǎo)入這些剛剛安裝完的模塊,其中dash-html-components用來生成HTML標(biāo)簽,dash-core-components模塊用來生成例如下拉框、輸入框等組件,這里我們還需要用到plotly模塊,因為我們需要用到的數(shù)據(jù)來自該模塊,里面是一眾互聯(lián)網(wǎng)公司過去一段時間中股價的走勢
import dash
import dash_html_components as html
import dash_core_components as dcc
import plotly.graph_objects as go
import plotly.express as px
那么我們讀取數(shù)據(jù)并且用plotly來繪制折線圖,代碼如下
app = dash.Dash() #實例化Dash
df = px.data.stocks() #讀取股票數(shù)據(jù)
def stock_prices():
# 繪制折線圖
fig = go.Figure([go.Scatter(x=df['date'], y=df['AAPL'],
line=dict(color='firebrick', width=4), name='Apple')
])
fig.update_layout(title='股價隨著時間的變幻',
xaxis_title='日期',
yaxis_title='價格'
)
return fig
app.layout = html.Div(id='parent', children=[
html.H1(id='H1', children='Dash 案例一', style={'textAlign': 'center',
'marginTop': 40, 'marginBottom': 40}),
dcc.Graph(id='line_plot', figure=stock_prices())
])
if __name__ == '__main__':
app.run_server()
我們點擊運行之后會按照提示將url復(fù)制到瀏覽器當(dāng)中便可以看到出來的結(jié)果了,如下所示
從代碼的邏輯上來看,我們通過Dash框架中的Div方法來進(jìn)行頁面的布局,其中有參數(shù)id來指定網(wǎng)頁中的元素,以及style參數(shù)來進(jìn)行樣式的設(shè)計,最后我們將會指出來的圖表放在dcc.Graph()函數(shù)當(dāng)中。
然后我們再添置一個下拉框,當(dāng)我們點擊這個下拉框的時候,可是根據(jù)我們的選擇展示不同公司的股價,代碼如下
dcc.Dropdown(id='dropdown',
options=[
{'label': '谷歌', 'value': 'GOOG'},
{'label': '蘋果', 'value': 'AAPL'},
{'label': '亞馬遜', 'value': 'AMZN'},
],
value='GOOG'),
output
options參數(shù)中的label對應(yīng)的是下拉框中的各個標(biāo)簽,而value對應(yīng)的是DataFrame當(dāng)中的列名
df.head()
output
最后我們將下拉框和繪制折線圖的函數(shù)給連接起來,我們點擊下拉框選中不同的選項的時候,折線圖也會相應(yīng)的產(chǎn)生變化,
@app.callback(Output(component_id='bar_plot', component_property='figure'),
[Input(component_id='dropdown', component_property='value')])
def graph_update(dropdown_value):
print(dropdown_value)
# Function for creating line chart showing Google stock prices over time
fig = go.Figure([go.Scatter(x=df['date'], y=df['{}'.format(dropdown_value)],
line=dict(color='firebrick', width=4))
])
fig.update_layout(title='股價隨著時間的變幻',
xaxis_title='日期',
yaxis_title='價格'
)
return fig
我們看到callback()方法中指定輸入和輸出的媒介,其中Input參數(shù),里面的component_id對應(yīng)的是下拉框的id也就是dropdown,而Output參數(shù),當(dāng)中的component_id對應(yīng)的是折線圖的id也就是bar_plot,我們來看一下最后出來的結(jié)果如下
最后,全部的代碼如下所示
*請認(rèn)真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。