Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537 Warning: error_log(/data/www/wwwroot/hmttv.cn/caches/error_log.php): failed to open stream: Permission denied in /data/www/wwwroot/hmttv.cn/phpcms/libs/functions/global.func.php on line 537
有許多JavaScript 庫(kù)可用于繪制不同的圖表,包括折線圖、條形圖、圖形等等。
如果您正在嘗試學(xué)習(xí)如何使用 JavaScript 在您的網(wǎng)站上動(dòng)態(tài)顯示數(shù)據(jù),Chart.js是您可以測(cè)試的庫(kù)之一。
React是最好的 JavaScript 框架之一,還提供了一組很酷的圖表庫(kù),您可以通過(guò)這些庫(kù)創(chuàng)建 Web 和混合應(yīng)用程序的酷界面。
開(kāi)始使用 Chart.js 開(kāi)發(fā)數(shù)據(jù)可視化的步驟是什么?
在本文中了解如何操作。
Chart.js 是一個(gè)開(kāi)源的數(shù)據(jù)可視化 JavaScript 庫(kù),可以繪制基于 HTML 的圖表。
它目前能夠支持八種可以動(dòng)畫的交互式圖表。要使用 chart.js 創(chuàng)建基于 HTML 的圖表,您需要一個(gè)HTML 畫布來(lái)顯示它。
該庫(kù)可用于一系列數(shù)據(jù)集和其他自定義參數(shù),如邊框顏色、背景顏色等。
其中之一的數(shù)據(jù)集稱為標(biāo)簽數(shù)據(jù)集,即 X 軸的值。另一個(gè)是數(shù)字的集合,通常沿著 Y 軸。
還需要在圖表對(duì)象內(nèi)部定義圖形類型,以確保庫(kù)可以確定要繪制什么圖形。
正如我們之前提到的,您可以使用 chart.js 制作各種圖表。
在本教程中,我們將從條形圖和折線圖開(kāi)始。一旦您了解了這些圖表類型的概念,您將擁有繪制其他可用圖表所需的信息和工具。
首先使用 chart.js,創(chuàng)建所需的文件。在本指南中,文件的名稱將是 chart.html、plot.js 和 index.css。您可以使用任何命名約定來(lái)命名您的文件。
然后,將以下代碼復(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)來(lái)設(shè)置它的樣式。當(dāng)您完成 HTML 或 CSS 文件并準(zhǔn)備好使用 JavaScript 創(chuàng)建圖表時(shí)。
對(duì)于要使用 chart.js 創(chuàng)建的折線圖,您需要將圖表類型更改為折線。這告訴庫(kù)如何繪制折線圖。
為了顯示這一點(diǎn),在 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í),使用其他數(shù)據(jù)或修改顏色以觀察發(fā)生的情況。
如您所見(jiàn),頂部附近有一個(gè)額外的圖例框。您可以將其從選項(xiàng)參數(shù)中取出。
除了刪除或添加圖例之外,它的選項(xiàng)參數(shù)還可用于進(jìn)行其他調(diào)整。例如,您可以應(yīng)用它來(lái)使軸從零開(kāi)始。
定義選項(xià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. } } });
輸出:
您還可以為每個(gè)點(diǎn)的背景選擇不同的顏色。然而,這種方式的背景顏色變化通常更適合條形圖。
這是唯一一次您必須將圖表類型更改為條形。無(wú)需更改顏色選項(xiàng)的選項(xiàng),因?yàn)闂l形將自動(dòng)繼承其背景顏色:
// 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è)置為從零或任何其他值開(kāi)始,就像您對(duì)折線圖所做的那樣。
要為每個(gè)條使用不同的顏色,您必須將與數(shù)據(jù)中的項(xiàng)目數(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. }});
輸出:
要?jiǎng)?chuàng)建餅圖,請(qǐng)將圖表類型切換為餅圖。也可以使圖例的顯示為真以確定餅圖的每個(gè)部分是什么:
// 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. } });
輸出:
就像您在前面的示例中所做的那樣,通過(guò)更改圖表類型來(lái)嘗試不同的圖表。
但是,支持一些 chart.js 圖表類型。chart.js 圖表類型,您可以使用上面的代碼約定:
盡管您在本教程中只熟悉了餅圖、折線圖和條形圖,但使用 chart.js 繪制其他圖表的 Code Pattern 也基于相同的原理。您也可以自由地嘗試其他圖表。
沒(méi)發(fā)現(xiàn) ECharts 這款神器的時(shí)候,之前所做的數(shù)據(jù)統(tǒng)計(jì)圖只能自個(gè)純手寫,倒也是可以實(shí)現(xiàn),只不過(guò)特別的費(fèi)時(shí)。后來(lái)無(wú)意中在網(wǎng)上瞄到 ECharts 這款專門用來(lái)生成數(shù)據(jù)圖表的插件,便嘗試了一下,那感覺(jué)真的不要太爽!
官方介紹
ECharts,一個(gè)使用 JavaScript 實(shí)現(xiàn)的開(kāi)源可視化庫(kù),可以流暢的運(yùn)行在 PC 和移動(dòng)設(shè)備上,兼容當(dāng)前絕大部分瀏覽器,底層依賴輕量級(jí)的矢量圖形庫(kù) ZRender,提供直觀,交互豐富,可高度個(gè)性化定制的數(shù)據(jù)可視化圖表。
獲取 ECharts
1、下載地址
https://github.com/apache/incubator-echarts
2、點(diǎn)擊紅色箭頭按鈕,將壓縮包下載下來(lái)
image
3、echarts 庫(kù)放在解壓后文件夾中的 dist 目錄里
image
將整個(gè) dist 目錄復(fù)制到你的項(xiàng)目中去,可重命名為 echarts
備注:若不想下載 ECharts 庫(kù)文件,可在頭部直接引用 bootcdn 上的 echarts 文件,地址為:
https://cdn.bootcss.com/echarts/4.2.1-rc1/echarts.min.js
繪制數(shù)據(jù)圖表
1、柱狀圖
柱狀圖效果預(yù)覽
代碼實(shí)現(xiàn)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>數(shù)據(jù)統(tǒng)計(jì)圖:柱狀圖</title> <!-- 引入 ECharts 文件 這里選擇min.js壓縮版的echarts --> <script src="echarts/echarts.min.js"></script> </head> <body> <!-- 為ECharts準(zhǔn)備一個(gè)具備大?。▽捀撸┑腄om --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基于準(zhǔn)備好的dom,初始化echarts實(shí)例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項(xiàng)和數(shù)據(jù) var option = { title: { text: '2014-2019年 前端人均工資' }, tooltip: {},//提示框組件(鼠標(biāo)移動(dòng)到數(shù)字表時(shí)觸發(fā)) xAxis: { //x軸 data: ["2014年","2015年","2016年","2017年","2018年","2019年"] }, yAxis: {},//y軸 內(nèi)容會(huì)自動(dòng)從以下的series.data 中獲取 series: [{ name: '人均工資', type: 'bar', //類型為:柱狀圖 data: [3800, 4600, 5100, 5800, 6300, 7300] //x軸項(xiàng)目對(duì)應(yīng)的數(shù)據(jù) }] }; // 使用剛指定的配置項(xiàng)和數(shù)據(jù)顯示圖表。 myChart.setOption(option); </script> </body> </html>
2、折線圖
折線圖效果預(yù)覽
代碼實(shí)現(xiàn)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>數(shù)據(jù)統(tǒng)計(jì)圖:折線圖</title> <!-- 引入 ECharts 文件 這里選擇min.js壓縮版的echarts --> <script src="echarts/echarts.min.js"></script> </head> <body> <!-- 為ECharts準(zhǔn)備一個(gè)具備大?。▽捀撸┑腄om --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基于準(zhǔn)備好的dom,初始化echarts實(shí)例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項(xiàng)和數(shù)據(jù) var option = { title: { text: '未來(lái)一周氣溫變化' }, 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], } ] }; // 使用剛指定的配置項(xiàng)和數(shù)據(jù)顯示圖表。 myChart.setOption(option); </script> </body> </html>
3、餅圖
餅圖效果預(yù)覽
代碼實(shí)現(xiàn)
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>數(shù)據(jù)統(tǒng)計(jì)圖:餅圖</title> <!-- 引入 ECharts 文件 這里選擇min.js壓縮版的echarts --> <script src="echarts/echarts.min.js"></script> </head> <body> <!-- 為ECharts準(zhǔn)備一個(gè)具備大小(寬高)的Dom --> <div id="main" style="width: 600px;height:400px;"></div> <script type="text/javascript"> // 基于準(zhǔn)備好的dom,初始化echarts實(shí)例 var myChart = echarts.init(document.getElementById('main')); // 指定圖表的配置項(xiàng)和數(shù)據(jù) var option = { title : { text: '某公司年齡階段的員工占比', x:'center'//水平居中 }, tooltip : {//提示框組件。 trigger: 'item', //'item' 數(shù)據(jù)項(xiàng)圖形觸發(fā),主要在散點(diǎn)圖,餅圖等無(wú)類目軸的圖表中使用。 formatter: "{a} <br/> : {c} (6ye8yaa%)" //{a}(系列名稱),(數(shù)據(jù)項(xiàng)名稱),{c}(數(shù)值), aqo8a4m(百分比) }, series : [ { name: '年齡占比', type: 'pie', radius : '55%',//餅圖的半徑 center: ['50%', '60%'],//餅圖的中心(圓心)坐標(biāo),數(shù)組的第一項(xiàng)是橫坐標(biāo),第二項(xiàng)是縱坐標(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)' } } } ] }; // 使用剛指定的配置項(xiàng)和數(shù)據(jù)顯示圖表。 myChart.setOption(option); </script> </body> </html>
結(jié)語(yǔ)
以上繪制的圖表是數(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
者: 俊欣
來(lái)源:關(guān)于數(shù)據(jù)分析與可視化
今天小編來(lái)為大家安利另外一個(gè)用于繪制可視化圖表的Python框架,名叫Dash,建立在Flask、Plotly.js以及React.js的基礎(chǔ)之上,在創(chuàng)建之出的目的是為了幫助前端知識(shí)匱乏的數(shù)據(jù)分析人員,以純Python編程的方式快速制作出交互特性強(qiáng)的數(shù)據(jù)可視化大屏,在經(jīng)過(guò)多年的迭代發(fā)展,如今不僅僅可以用來(lái)開(kāi)發(fā)在線數(shù)據(jù)可視化作品,即便是輕量級(jí)的數(shù)據(jù)儀表盤、BI應(yīng)用甚至是博客或者是常規(guī)的網(wǎng)站都隨處可見(jiàn)Dash框架的影子,今天小編就先來(lái)介紹一下該框架的一些基礎(chǔ)知識(shí),并且來(lái)制作一個(gè)簡(jiǎn)單的數(shù)據(jù)可視化大屏。
我們先來(lái)了解一下Dash框架中的兩個(gè)基本概念
Layout顧名思義就是用來(lái)設(shè)計(jì)可視化大屏的外觀和布局,添加一些例如下拉框、單選框、復(fù)選框、輸入框、文本框、滑動(dòng)條等組件,其中Dash框架對(duì)HTML標(biāo)簽也進(jìn)行了進(jìn)一步的封裝,使得我們直接可以通過(guò)Python代碼來(lái)生成和設(shè)計(jì)每一個(gè)網(wǎng)頁(yè)所需要的元素,例如
<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ù),基本上是以裝飾器的形式來(lái)體現(xiàn)的,實(shí)現(xiàn)前后端異步通信的交互,例如我們?cè)邳c(diǎn)擊按鈕或者下拉框之后出現(xiàn)的功能就是通過(guò)回調(diào)函數(shù)來(lái)實(shí)現(xiàn)的。
在導(dǎo)入模塊之前,我們先用pip命令來(lái)進(jìn)行安裝,
! pip install dash
! pip install dash-html-components
! pip install dash-core-components
! pip install plotly
然后我們導(dǎo)入這些剛剛安裝完的模塊,其中dash-html-components用來(lái)生成HTML標(biāo)簽,dash-core-components模塊用來(lái)生成例如下拉框、輸入框等組件,這里我們還需要用到plotly模塊,因?yàn)槲覀冃枰玫降臄?shù)據(jù)來(lái)自該模塊,里面是一眾互聯(lián)網(wǎng)公司過(guò)去一段時(shí)間中股價(jià)的走勢(shì)
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來(lái)繪制折線圖,代碼如下
app = dash.Dash() #實(shí)例化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='股價(jià)隨著時(shí)間的變幻',
xaxis_title='日期',
yaxis_title='價(jià)格'
)
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()
我們點(diǎn)擊運(yùn)行之后會(huì)按照提示將url復(fù)制到瀏覽器當(dāng)中便可以看到出來(lái)的結(jié)果了,如下所示
從代碼的邏輯上來(lái)看,我們通過(guò)Dash框架中的Div方法來(lái)進(jìn)行頁(yè)面的布局,其中有參數(shù)id來(lái)指定網(wǎng)頁(yè)中的元素,以及style參數(shù)來(lái)進(jìn)行樣式的設(shè)計(jì),最后我們將會(huì)指出來(lái)的圖表放在dcc.Graph()函數(shù)當(dāng)中。
然后我們?cè)偬碇靡粋€(gè)下拉框,當(dāng)我們點(diǎn)擊這個(gè)下拉框的時(shí)候,可是根據(jù)我們的選擇展示不同公司的股價(jià),代碼如下
dcc.Dropdown(id='dropdown',
options=[
{'label': '谷歌', 'value': 'GOOG'},
{'label': '蘋果', 'value': 'AAPL'},
{'label': '亞馬遜', 'value': 'AMZN'},
],
value='GOOG'),
output
options參數(shù)中的label對(duì)應(yīng)的是下拉框中的各個(gè)標(biāo)簽,而value對(duì)應(yīng)的是DataFrame當(dāng)中的列名
df.head()
output
最后我們將下拉框和繪制折線圖的函數(shù)給連接起來(lái),我們點(diǎn)擊下拉框選中不同的選項(xiàng)的時(shí)候,折線圖也會(huì)相應(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='股價(jià)隨著時(shí)間的變幻',
xaxis_title='日期',
yaxis_title='價(jià)格'
)
return fig
我們看到callback()方法中指定輸入和輸出的媒介,其中Input參數(shù),里面的component_id對(duì)應(yīng)的是下拉框的id也就是dropdown,而Output參數(shù),當(dāng)中的component_id對(duì)應(yīng)的是折線圖的id也就是bar_plot,我們來(lái)看一下最后出來(lái)的結(jié)果如下
最后,全部的代碼如下所示
*請(qǐng)認(rèn)真填寫需求信息,我們會(huì)在24小時(shí)內(nèi)與您取得聯(lián)系。