Python matplotlib – 1

In this article:

  1. A simple graphic with pyplot
  2. Using lists for graphic coordinates
  3. A graphic with many lines
  4. Using tuples for graphic coordinates
  5. What happen when lists or tuples for coordinates have different size?
  6. Save graphic in a file

1. A simple graphic with pyplot

Most simple graphic with matplotlib is plotting with pyplot interface:

import matplotlib.pyplot as myplot
myplot.plot([1, 5], [2, 12])
myplot.show()

This show graphic like below:

Simple graphic with mathplotlib pyplot.

From image result that pyplot draw a line between two points (1,2) and (5,12)

2. Using lists for graphic coordinates

Arguments for "plot" in myplot.plot([1, 5], [2, 12]) are 2 lists:
l1 = [1, 5]
l2 = [2, 12]

The same graphic is obtained using:

import matplotlib.pyplot as myplot
l1 = [1, 5]
l2 = [2, 12]
myplot.plot(l1, l2)
myplot.show()

In this case line draw is between
point 1 with coordinates:
x=first element of list l1, or l1[0]
y=first element of list l2, or l2[0]
point 2 with coordinates:
x=second element of list l1, or l1[1]
y=second element of list l2, or l2[1]

3. A graphic with many lines

If lists l1 and l2 have more elements, plot will draw line(es) between appropriate points. For example:

import matplotlib.pyplot as myplot
l1 = [1, 3, 5]
l2 = [2, 4, 12]
myplot.plot(l1, l2)
myplot.show()

Code will draw:

A pyplot graphic with many lines

In this case lines are between points that have coordinates:
(1,2), (3,4), (5,12)
or
(l1[0],l2[0]), (l1[0],l2[0]), (l1[0],l2[0])

4. Using tuples for graphic coordinates

The same graphic is obtained if we use tuples, i.e. code:

import matplotlib.pyplot as myplot
t1 = (1, 3, 5)
t2 = (2, 4, 12)
myplot.plot(t1, t2)
myplot.show()

Lists or tuples can have more elements, it is important that those to have
the same number of elements.

5. What happen when lists or tuples for coordinates have different size?

If we try with different elements, for example code:

import matplotlib.pyplot as myplot
l1 = [1, 3, 5]
l2 = [2, 4, 7, 12]
myplot.plot(l1, l2)
myplot.show()

this will fail with error:
ValueError: x and y must have same first dimension, but have shapes (3,) and (4,)

6. Save graphic in a file

Command myplot.show() display effectively resulted graphic.
Using savefig() graphic is saved in a file for example:

import matplotlib.pyplot as myplot
l1 = [1, 3, 5]
l2 = [2, 4, 12]
myplot.plot(l1, l2)
myplot.savefig("C:\tmp\fig1.png")

Here savefig method is used with only one parameter, the file path.
Method savefig have many more parameters, like here.
Above code will save graphic in file C:\tmp\fig1.png

MySQL-Python – 5 Logging and MySQL Connector

This is a continuation from previous post MySQL-Python - 4.

In this page:


1. About logging

Logging activity for MySQL connector use default Python logging features. By default events with level WARNING are logged and are printed to terminal where we run, i.e. sys.stderr 

Configuring logging, we can change logged events level and we can print messages to other destination than stderr.


2. Sample code for classical logging

Below is a sample code for logging used in case when MySql Connector is used with insert. Use can be similar for other MySQL connector usecase. 

import logging

import datetime

import mysql.connector


#--this is code for loggers

logger = logging.getLogger("mysql.connector")

logger.setLevel(logging.DEBUG)


formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s- %(message)s")


# create console handler named stream_handler

stream_handler = logging.StreamHandler()

# add formatter to stream_handler

stream_handler.setFormatter(formatter)

# add  console handler  stream_handler to logger

logger.addHandler(stream_handler)

# create a file handler

file_handler = logging.FileHandler("conn_log.log")

# add formatter to file handler

file_handler.setFormatter(formatter)

# add  file handler to logger

logger.addHandler(file_handler)


#---this is code where mysql connector is used

connection = mysql.connector.connect(user='u2024', password='password1234', host='localhost', port=3306, database='sakila')

logger.debug('user u2024 logged')

cursor = connection.cursor()

logger.info('mysql.connector created cursor')


SQL_insert_actor = ("INSERT INTO actor (first_name, last_name, last_update)"

            "VALUES  (%s, %s, %s)")

values_for_actor = ('NICK','WALKEN', datetime.date(2023, 12, 16))

cursor.execute(SQL_insert_actor, values_for_actor)

# commit to the database

connection.commit()

logger.info('mysql.connector entry inserted in DB')


cursor.close()

connection.close() 


3. Code comments

First we defined a logger using logger = logging.getLogger("mysql.connector"), here mysql.connector is the logger name, it can be anything, we  named it  mysql.connector for visibility.

Change log level to DEBUG using logger.setLevel(logging.DEBUG)

Permitted log level are here

Line: formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s- %(message)s") 

define how log record will appear. This line is not mandatory, if we not use it, by default will be used string like '%(message)s' which means only the message will be in log record.

In our example we use a formatter object  thus we will display in log line: time, name, log level of the message and message itself. More about possibility for format message in formatter-objects


Next lines:

# create console handler named stream_handler

stream_handler = logging.StreamHandler()

# add formatter to stream_handler

stream_handler.setFormatter(formatter)

# add  console handler  stream_handler to logger

logger.addHandler(stream_handler)


create a stream handler that is added to logger, this stream handler is for logging to console, means lines for example that appear if we run python script in command prompt, or lines that appear on the screen as we will see when run in PyCharm


Lines:

file_handler = logging.FileHandler("conn_log.log")

# add formatter to file handler

file_handler.setFormatter(formatter)

# add  file handler to logger

logger.addHandler(file_handler)


those create a file handler and add it to logger, those lines are responsible for what will be written in log file named "conn_log.log".


All the lines that follow after 

#---this is code where mysql connector is used

are to exemplify. From mysql connector point of view, those contain lines for inserting in DB. 

Between those lines, we added lines for logging, those contain logger.debug or logger.info

For example line like 

logger.debug('user u2024 logged')

will sent message 'user u2024 logged' with proper formatting, to console or file.


4. Sample logging output 

Below is an image with sample code run in Pycharm.


Logging in mysql connector, PyCharm


We see with red lines in output log lines from console handler defined prior. 

In  file "conn_log.log" appear also lines, this time from file handler. Below is how file looks like: 

Logging in file