Chapter 4:
Create a histogram

Let’s now write a function that creates a histogram of the hours in the Date/Time column that we can then plot on our self.bar_chart.

Step 1: Return the dataframe from get_uber_data

First, we need to modify the get_uber_data function to return the dataframe instead of just the head. We also need to convert the values in the Date/Time column to be datetime objects. We can also remove @anvil.server.callable from the function since we won’t need to call it from the client. The function should now look like this:

def get_uber_data():
  #read in 10000 rows of data 
  df = pd.read_csv(data_files['uber-raw-data-sep14.csv'], nrows=10000)
  df['Date/Time'] = pd.to_datetime(df['Date/Time'])
  return df

Next, we need to call the function from the server module:

DATA = get_uber_data()

Step 2: Create a numpy histogram

Let’s now add a function to create a histogram of the values in the Date/Time column. We’ll make this function callable from our client Form.

We can use numpy’s histogram method to count the number of entries in our dataset per hour. This method returns two arrays, but we only care about the first, which is an array of the histogram values.

def create_histogram():
  histogram = np.histogram(DATA['Date/Time'].dt.hour, bins=24)[0]
  return histogram

Step 3: Add data to self.bar_chart

Finally, we need to switch back to our Form code and in the Form’s __init__ method, set the data of the bar_chart plot to be a Plotly go.Bar object where the y-axis values are the histogram values. Remove"get_uber_data") and replace it with: = go.Bar('create_histogram'))

Click the green Run button at the top of the Anvil Editor to run the app. If we’ve done everything correctly, the app should look like this:

Screenshot of the app running. The bar chart is populate but doesn't match the app theme.

The plot is right, but it looks…wrong. Go back to the Form code and add Plot.templates.default = 'rally' to the __init__ function. This will give all Plots in our app the Rally theme (the same theme as our app). Run the app again, and it should look much better:

Screenshot of the app running. The bar chart now has the same theme as the app.

In the next chapter, we’ll use Plotly to plot the location data onto a Mapbox map.

Chapter complete

Congratulations, you've completed this chapter!