[英]How to implement Highcharts column-drilldown chart in Rails application?
[英]rails and highcharts column chart
嗨,我真的在我的rails應用程序中使用highcharts停留在即時通訊上,並試圖獲取柱形圖以顯示與數據庫中的女性用戶相比,我有多少男性用戶,但似乎無法弄清楚如何從用戶數據庫中讀取數據表。 這是我的用戶模型
def self.gender_analysis(gender)
User.where(:gender => MALE).count
User.where(:gender => FEMALE).count
end
這是我的user.js文件,我在其中創建圖表
$(function(){
new Highcharts.Chart({
chart:{
renderTo: "pie_chart",
type:"column"
},
title: { text: "Gender" },
xAxis: { type: "percent correct"},
yAxis: {
title: { text: "Gender" }
},
series: [{
data: <%= users.each do |user| %>
}]
});
});
而我的用戶view.html.erb看起來像
<div id="pie_chart" style="width:568px; height:300px;"></div>
<h1>Listing users</h1>
<table>
<thead>
<tr>
<th>Number</th>
<th>Gender</th>
<th>Hobby</th>
<th>Created</th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% @users.each do |user| %>
<tr>
<td><%= user.number %></td>
<td><%= user.gender %></td>
<td><%= user.hobby %></td>
<td><%= user.created_at %></td>
我是Rails開發的新手,將不勝感激
應該是這樣的:
def self.gender_analysis(gender)
User.where(:gender => MALE).count if gender == :male
User.where(:gender => FEMALE).count if gender == :female
end
然后在您的ERB文件中應具有以下內容:
$(function(){
new Highcharts.Chart({
chart:{
renderTo: "pie_chart",
type:"column"
},
title: { text: "Gender" },
xAxis: { type: "percent correct"},
yAxis: {
title: { text: "Gender" }
},
,
series: [{
type: 'pie',
name: 'Gender Split',
data: [
['Female', <%= User.gender_analysis(:female) %>],
['Male', <%= User.gender_analysis(:male) %>]
]
}]
});
});
很簡單:在您view
,我的意思是在您的html.erb
放:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>
並添加script
:
$(function () {
$('#container').highcharts({
chart: {
type: 'column'
},
title: {
text: 'Total User'
},
subtitle: {
text: 'Source: Unknown'
},
xAxis: {
categories: ['Male', 'Female'],
title: {
text: null
}
},
yAxis: {
min: 0,
title: {
text: 'Total Number',
align: 'high'
},
labels: {
overflow: 'justify'
}
},
tooltip: {
valueSuffix: ''
},
plotOptions: {
bar: {
dataLabels: {
enabled: true
}
}
},
credits: {
enabled: false
},
series: [{
name: 'Users',
data: [<%= User.where(:gender => 'MALE').count %>, <%= User.where(:gender => 'FEMALE').count %>]
}]
});
});
也可以在這里查看小提琴。
編碼愉快! :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.