I wanted to implement the graph function in Rails, so I used Chartkick. Since there were few articles in the middle, I decided to post it as a reference. This time, gem groupdate is used to get the update date and time. The gems used are as follows.
① Install gem
gem chartkick gem groupdate
//= require chartkick //= require Chart.bundle
④ Described in the controller
def index @users_count = User.group_by_day(:created_at).size #User registration number graph output The above description cannot be used unless gem group date is installed. @user_today = User.where(created_at: Date.today.all_day).count #Number of registered users per day end
⑤ Described in view
<div class="main"> <label class="text-user">Number of registered members by day(Total number of members: <%= @users.count %>)</label> <div class="graph"> <%= line_chart @users_count, download: true, colors: ['#FF4F02'] %> </div> </div>
⑥ Actual screen (registration date and number of registrations)
line_chart --Used for line graph output. In addition, pie_chart (pie chart), column_chart (bar chart), bar_chart (bar chart horizontal direction), area_chart (area chart), scatter_chart (scatter chart), etc. can be used.
colors: ['rgb'] --You can change the color of the lines in the graph.
--groupdate handles date and time data based on a given time zone. After installing groupdate, the following methods are available. Reference https://github.com/ankane/groupdate
group_by_second (time every 2 minutes) group_by_minute (minutes) group_by_hour (hours) group_by_day (date) group_by_week (week) group_by_month (Monday) group_by_quarter (quarter) group_by_year (year) group_by_hour_of_day (returns both day and time) group_by_day_of_week (returns the date of the week) group_by_day_of_month (every day of the month) group_by_month_of_year
Reference (1) Use bar graph column_chart
Reference ③ Pie chart using pie_chart
The group_by part is ambiguous, but if it is wrong, please point it out. The chart kick is also available on the official website with images so it is easy to understand how to use it, so please refer to it.