Output simple graph with Rails Use gem-chartkick / groupdate

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.

Development environment

Rails 5.2.4

Build

① Install gem

gem chartkick
gem groupdate

② Terminal

 bundle install

③ Read Javascript library Added the following to app / assets / javascripts / application.js.

application.js


//= require chartkick
//= require Chart.bundle

④ Described in the controller

top.rb


  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

index.html.erb


	<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) guraf.jpg

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.

About gem group date

--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 スクリーンショット 2020-07-16 18.13.32.png

Reference ③ Pie chart using pie_chart スクリーンショット 2020-07-16 18.13.47.png

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.

Recommended Posts

Output simple graph with Rails Use gem-chartkick / groupdate
[Docker] Use whenever with Docker + Rails
Use Microsoft Graph with standard Java
[Rails withdrawal] Create a simple withdrawal function with rails
[Rails 6] Interactive graph drawing with Ajax + chart.js
[Rails] Use jQuery