Bar Chart-Daily output - From InfluxDB

I could not find a lovelace card to show barchart for daily output and I couldn’t modify mini-graph-card with my limited programming ability. Hence made an app to show bar chart of my Daily Power Output as an Image

# -*- coding: utf-8 -*-
"""App to plot monthly data from InfluxDB.
Args:
class: InfluxChart
  module: influx_chart
  host: localhost #influxdb host
  user: home_assistant #influxdb user name
  password: 'pwd' #influxdb pwd
  dbname: home_assistant #influxdb db name
  query: "select max(value) from kWh where entity_id = 'energy_generation' and time >= now() - 30d group by time(1d) fill(null) order by time asc;"
  
"""
import appdaemon.plugins.hass.hassapi as hass
from influxdb import InfluxDBClient
import datetime
import matplotlib.pyplot as plt

class InfluxChart(hass.Hass):
    
    def initialize(self):
        self.log("Hello from InfluxChart Data Plot App")
        self.host = self.args.get("host", "localhost")
        port=8086
        self.user = self.args.get("user", "home_assistant")
        self.password = self.args.get("password", None)
        self.dbname = self.args.get("dbname", "home_assistant")
        self.query = self.args.get("query", None)
        #run at midnight
        self.run_daily(self.create_chart, datetime.time(23, 55, 0))
    
    def create_chart(self, kwargs):
        self.log("Querying data: ")
        """Instantiate a connection to the InfluxDB."""
        client =InfluxDBClient(self.host, port, self.user, self.password, self.dbname)
        result = client.query(self.query)
        resultInList = list(result.get_points(measurement='kWh'))
        data = {}
        for p in resultInList:
           d = p['time']
           mt = d.split('-')[1]
           dt = ((d.split('-')[2].split(':')[0])).split('T')[0]
           k = "{}/{}".format(mt,dt)
           data[k] = p['max']
        names = list(data.keys())
        values = list(data.values())
        self.plot_bar_chart(values, names, data)

        
    def plot_bar_chart(self,values, labels, data):
        #set tick label font size
        plt.rc('xtick',labelsize=6)
        plt.rc('ytick',labelsize=6)
        #Plot size
        plt.figure(figsize=(6,3.5))
        h = plt.bar(range(len(labels)), values, label=labels, color='#039BE5')
        plt.subplots_adjust(bottom=0.3)
        ax = plt.gca()
        xticks_pos = [0.5*patch.get_width() + patch.get_xy()[0] for patch in h]
        plt.xlim([-0.5,len(labels)-0.5])
        #hide top and right axis lines
        ax.spines['top'].set_visible(False)
        ax.spines['right'].set_visible(False)
        #plt.tick_params(axis="both", which="both", bottom="on", top="off",
                #labelbottom="on", left="on", right="off", labelleft="on")
        #rotate bottom tick labels
        plt.xticks(xticks_pos, labels,  ha='center', rotation=90, fontsize=6)
        #y axis label
        plt.ylabel('kWh', fontsize=10)
        plt.title('DAILY ELECTRICITY OUTPUT', fontsize=10)
        #plt.savefig('top_words.png', bbox_inches='tight') 
        plt.savefig('/home/anilet/appdaemon/conf/apps/influx_chart/bar.png', bbox_inches='tight') 

bar

2 Likes

save the pic on the right place (inside custom_css for instance) and you can show it on a Dashboard
save it in the www dir from HA and you can use it directly in lovelace.

I am using the picture-entity card to show as a local-camera entity

1 Like

When I try this, I get an error that influxdb module is not found. this post is old - any update?

Thanks

In Home Assistant, you need to make sure that the influxdb package is installed for AppDaemon to access. To do this, go to AppDaemon under Add-ons, then go to the Configuration tab, and type β€œinfluxdb” in the Python packages textbox under Options. Then click Save and let AppDaemon restart.

Hi,
Is the advice above still valid or is there a different approach now?
I added the influxdb to the Python package textbox and restarted AppDaemon but I am still getting

ImportError: cannot import name 'InfluxDBClient' from 'influxdb' (/config/apps/influxdb.py)

it also seems that the influxdb package has installed correctly

Looking in indexes: https://pypi.org/simple, https://wheels.home-assistant.io/musllinux-index/
Collecting influxdb
  Downloading influxdb-5.3.2-py2.py3-none-any.whl.metadata (6.9 kB)
Requirement already satisfied: python-dateutil>=2.6.0 in /usr/lib/python3.11/site-packages (from influxdb) (2.8.2)
Requirement already satisfied: pytz in /usr/lib/python3.11/site-packages (from influxdb) (2023.3.post1)
Requirement already satisfied: requests>=2.17.0 in /usr/lib/python3.11/site-packages (from influxdb) (2.28.2)
Requirement already satisfied: six>=1.10.0 in /usr/lib/python3.11/site-packages (from influxdb) (1.16.0)
Collecting msgpack (from influxdb)
  Downloading msgpack-1.0.8-cp311-cp311-musllinux_1_1_x86_64.whl.metadata (9.1 kB)
Requirement already satisfied: charset-normalizer<4,>=2 in /usr/lib/python3.11/site-packages (from requests>=2.17.0->influxdb) (3.3.2)
Requirement already satisfied: idna<4,>=2.5 in /usr/lib/python3.11/site-packages (from requests>=2.17.0->influxdb) (3.7)
Requirement already satisfied: urllib3<1.27,>=1.21.1 in /usr/lib/python3.11/site-packages (from requests>=2.17.0->influxdb) (1.26.18)
Requirement already satisfied: certifi>=2017.4.17 in /usr/lib/python3.11/site-packages (from requests>=2.17.0->influxdb) (2024.2.2)
Downloading influxdb-5.3.2-py2.py3-none-any.whl (79 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 79.4/79.4 kB 1.8 MB/s eta 0:00:00
Downloading msgpack-1.0.8-cp311-cp311-musllinux_1_1_x86_64.whl (409 kB)
   ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 409.1/409.1 kB 6.3 MB/s eta 0:00:00
Installing collected packages: msgpack, influxdb
Successfully installed influxdb-5.3.2 msgpack-1.0.8
WARNING: Running pip as the 'root' user can result in broken permissions and conflicting behaviour with the system package manager. It is recommended to use a virtual environment instead: