100% found this document useful (3 votes)
23 views

(Ebook) Web App Development and Real-Time Web Analytics with Python: Develop and Integrate Machine Learning Algorithms into Web Apps by Nokeri, Tshepo Chris ISBN 9781484277829, 1484277821 - Explore the complete ebook content with the fastest download

The document provides information about various ebooks related to web app development, including titles by different authors and their respective ISBNs. It highlights the availability of instant ebook downloads in multiple formats at ebooknice.com. Additionally, it mentions specific topics covered in the ebooks, such as machine learning integration and real-time web analytics using Python.

Uploaded by

siisikisper
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (3 votes)
23 views

(Ebook) Web App Development and Real-Time Web Analytics with Python: Develop and Integrate Machine Learning Algorithms into Web Apps by Nokeri, Tshepo Chris ISBN 9781484277829, 1484277821 - Explore the complete ebook content with the fastest download

The document provides information about various ebooks related to web app development, including titles by different authors and their respective ISBNs. It highlights the availability of instant ebook downloads in multiple formats at ebooknice.com. Additionally, it mentions specific topics covered in the ebooks, such as machine learning integration and real-time web analytics using Python.

Uploaded by

siisikisper
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 81

Instant Ebook Access, One Click Away – Begin at ebooknice.

com

(Ebook) Web App Development and Real-Time Web


Analytics with Python: Develop and Integrate
Machine Learning Algorithms into Web Apps by
Nokeri, Tshepo Chris ISBN 9781484277829,
1484277821
https://ebooknice.com/product/web-app-development-and-real-
time-web-analytics-with-python-develop-and-integrate-
machine-learning-algorithms-into-web-apps-36127710

OR CLICK BUTTON

DOWLOAD EBOOK

Get Instant Ebook Downloads – Browse at https://ebooknice.com


Instant digital products (PDF, ePub, MOBI) ready for you
Download now and discover formats that fit your needs...

Start reading on any device today!

(Ebook) Web App Development Made Simple with Streamlit: A web developer's guide to
effortless web app development, deployment by Rosario Moscato

https://ebooknice.com/product/web-app-development-made-simple-with-streamlit-a-
web-developer-s-guide-to-effortless-web-app-development-deployment-56268460

ebooknice.com

(Ebook) Real-Time Twilio and Flybase. Build Real-Time Web Apps Using Twilio and
Flybase with Node.js by Roger Stringer ISBN 9781484270738, 9781484270745,
1484270738, 1484270746

https://ebooknice.com/product/real-time-twilio-and-flybase-build-real-time-web-
apps-using-twilio-and-flybase-with-node-js-33765234

ebooknice.com

(Ebook) Beginning Android Web Apps Development: Develop for Android using HTML5,
CSS3, and JavaScript by Unknown

https://ebooknice.com/product/beginning-android-web-apps-development-develop-
for-android-using-html5-css3-and-javascript-55872370

ebooknice.com

(Ebook) Learning Web App Development by Semmy Purewal ISBN 9781449370190, 1449370195

https://ebooknice.com/product/learning-web-app-development-4656188

ebooknice.com
(Ebook) Web Development with Clojure: Build Bulletproof Web Apps with Less Code by
Dmitri Sotnikov ISBN 9781937785642, 1937785645

https://ebooknice.com/product/web-development-with-clojure-build-bulletproof-
web-apps-with-less-code-4727458

ebooknice.com

(Ebook) Web Development with Clojure: Build Bulletproof Web Apps with Less Code by
Dmitri Sotnikov ISBN 9781680500820, 1680500821

https://ebooknice.com/product/web-development-with-clojure-build-bulletproof-
web-apps-with-less-code-5767486

ebooknice.com

(Ebook) Flask Web Development: Developing Web Applications with Python by Miguel
Grinberg ISBN 9781449372620, 1449372627

https://ebooknice.com/product/flask-web-development-developing-web-applications-
with-python-4680280

ebooknice.com

(Ebook) Flask Web Development: Developing Web Applications With Python by Miguel
Grinberg ISBN 9781491991732, 1491991739

https://ebooknice.com/product/flask-web-development-developing-web-applications-
with-python-10539006

ebooknice.com

(Ebook) Flask Web Development: Developing Web Applications With Python by Miguel
Grinberg ISBN 9781491991732, 1491991739

https://ebooknice.com/product/flask-web-development-developing-web-applications-
with-python-7316108

ebooknice.com
Web App Development
and Real-Time Web
Analytics with Python
Develop and Integrate Machine Learning
Algorithms into Web Apps

Tshepo Chris Nokeri
Web App Development
and Real-Time Web
Analytics with Python
Develop and Integrate Machine
Learning Algorithms into Web Apps

Tshepo Chris Nokeri


Web App Development and Real-Time Web Analytics with Python: Develop and
Integrate Machine Learning Algorithms into Web Apps

Tshepo Chris Nokeri


Pretoria, South Africa

ISBN-13 (pbk): 978-1-4842-7782-9 ISBN-13 (electronic): 978-1-4842-7783-6


https://doi.org/10.1007/978-1-4842-7783-6

Copyright © 2022 by Tshepo Chris Nokeri


This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the
material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation,
broadcasting, reproduction on microfilms or in any other physical way, and transmission or information
storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now
known or hereafter developed.
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with
every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an
editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the
trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not
identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to
proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication,
neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or
omissions that may be made. The publisher makes no warranty, express or implied, with respect to the
material contained herein.
Managing Director, Apress Media LLC: Welmoed Spahr
Acquisitions Editor: Celestin Suresh John
Development Editor: James Markham
Coordinating Editor: Mark Powers
Cover designed by eStudioCalamar
Cover image by Andrew Kliatskyi on Unsplash (www.unsplash.com)
Distributed to the book trade worldwide by Apress Media, LLC, 1 New York Plaza, New York, NY 10004,
U.S.A. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.
springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science
+ Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.
For information on translations, please e-mail [email protected]; for reprint,
paperback, or audio rights, please e-mail [email protected].
Apress titles may be purchased in bulk for academic, corporate, or promotional use. eBook versions and
licenses are also available for most titles. For more information, reference our Print and eBook Bulk Sales
web page at http://www.apress.com/bulk-sales.
Any source code or other supplementary material referenced by the author in this book is available to
readers on GitHub via the book’s product page, located at www.apress.com/9781484277829. For more
detailed information, please visit http://www.apress.com/source-­code.
Printed on acid-free paper
I would like dedicate this book to my family, friends, and
anyone who played a pivotal role in any aspect of my life,
including the Apress team for the continous support.
Table of Contents
About the Author����������������������������������������������������������������������������������������������������� xi

About the Technical Reviewer������������������������������������������������������������������������������� xiii


Acknowledgments���������������������������������������������������������������������������������������������������xv

Chapter 1: Tabulating Data and Constructing Static 2D and 3D Charts�������������������� 1


Tabulating the Data����������������������������������������������������������������������������������������������������������������������� 1
2D Charting����������������������������������������������������������������������������������������������������������������������������������� 4
Box-Whisker Plot��������������������������������������������������������������������������������������������������������������������� 6
Histogram�������������������������������������������������������������������������������������������������������������������������������� 7
Line Plot����������������������������������������������������������������������������������������������������������������������������������� 8
Scatter Plot������������������������������������������������������������������������������������������������������������������������������ 9
Density Plot��������������������������������������������������������������������������������������������������������������������������� 10
Violin Plot������������������������������������������������������������������������������������������������������������������������������� 11
Regression Plot��������������������������������������������������������������������������������������������������������������������� 13
Joint Plot������������������������������������������������������������������������������������������������������������������������������� 13
Heatmap�������������������������������������������������������������������������������������������������������������������������������� 14
3D Charting��������������������������������������������������������������������������������������������������������������������������������� 17
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 19

Chapter 2: Interactive Tabulation and Charting������������������������������������������������������ 21


Plotly������������������������������������������������������������������������������������������������������������������������������������������� 21
Tabulating the Data with Plotly��������������������������������������������������������������������������������������������������� 22
Interactive Charting��������������������������������������������������������������������������������������������������������������������� 23
2D Charting��������������������������������������������������������������������������������������������������������������������������������� 23
Box Plot��������������������������������������������������������������������������������������������������������������������������������� 26
Violin Plot������������������������������������������������������������������������������������������������������������������������������� 27
Histogram������������������������������������������������������������������������������������������������������������������������������ 28

v
Table of Contents

Scatter Plot���������������������������������������������������������������������������������������������������������������������������� 32
Density Plot��������������������������������������������������������������������������������������������������������������������������� 34
Bar Chart������������������������������������������������������������������������������������������������������������������������������� 36
Pie Chart�������������������������������������������������������������������������������������������������������������������������������� 38
Sunburst�������������������������������������������������������������������������������������������������������������������������������� 38
Choropleth Map��������������������������������������������������������������������������������������������������������������������������� 41
Heatmap�������������������������������������������������������������������������������������������������������������������������������� 42
3D Charting��������������������������������������������������������������������������������������������������������������������������������� 43
Indicators������������������������������������������������������������������������������������������������������������������������������������ 44
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 45

Chapter 3: Containing Functionality and Styling for Interactive Charts����������������� 47


Updating Graph Layout���������������������������������������������������������������������������������������������������������������� 47
Updating Plotly Axes�������������������������������������������������������������������������������������������������������������� 48
Including Range Slider���������������������������������������������������������������������������������������������������������� 48
Including Buttons to a Graph������������������������������������������������������������������������������������������������� 49
Subplots�������������������������������������������������������������������������������������������������������������������������������������� 51
Styling Charts������������������������������������������������������������������������������������������������������������������������������ 56
Altering Color Schemes��������������������������������������������������������������������������������������������������������� 57
Color Sequencing������������������������������������������������������������������������������������������������������������������ 57
Customizing Traces���������������������������������������������������������������������������������������������������������������� 59
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 61

Chapter 4: Essentials of HTML�������������������������������������������������������������������������������� 63


Communication Between a Web Browser and a Web Server������������������������������������������������������ 63
URL Structure������������������������������������������������������������������������������������������������������������������������������ 63
Domain Hosting��������������������������������������������������������������������������������������������������������������������������� 64
Shared Web Hosting�������������������������������������������������������������������������������������������������������������� 64
Managed Web Hosting����������������������������������������������������������������������������������������������������������� 65
Web Servers�������������������������������������������������������������������������������������������������������������������������� 66
HyperText Markup Language������������������������������������������������������������������������������������������������������ 66
HTML Elements��������������������������������������������������������������������������������������������������������������������� 67

vi
Table of Contents

Meta Tag������������������������������������������������������������������������������������������������������������������������������������� 75
Practical Example����������������������������������������������������������������������������������������������������������������������� 75
Viewing Web Page Source���������������������������������������������������������������������������������������������������������� 78
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 78

Chapter 5: Python Web Frameworks and Apps������������������������������������������������������ 79


Web Frameworks������������������������������������������������������������������������������������������������������������������������ 79
Web Apps������������������������������������������������������������������������������������������������������������������������������������ 80
Flask������������������������������������������������������������������������������������������������������������������������������������������� 80
WSGI�������������������������������������������������������������������������������������������������������������������������������������� 80
Werkzeug������������������������������������������������������������������������������������������������������������������������������� 80
Jinja��������������������������������������������������������������������������������������������������������������������������������������� 81
Installing Flask���������������������������������������������������������������������������������������������������������������������� 81
Initializing a Flask Web App��������������������������������������������������������������������������������������������������� 81
Flask App Code���������������������������������������������������������������������������������������������������������������������� 82
Deploy a Flask Web App�������������������������������������������������������������������������������������������������������� 82
Dash�������������������������������������������������������������������������������������������������������������������������������������������� 82
Installing Dash Dependencies����������������������������������������������������������������������������������������������� 83
Initializing a Dash Web App��������������������������������������������������������������������������������������������������� 83
Dash Web App Code��������������������������������������������������������������������������������������������������������������� 83
Deploy a Dash Web App��������������������������������������������������������������������������������������������������������� 84
Jupyter Dash������������������������������������������������������������������������������������������������������������������������������� 84
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 85

Chapter 6: Dash Bootstrap Components����������������������������������������������������������������� 87


Number Input������������������������������������������������������������������������������������������������������������������������������ 88
Text Area������������������������������������������������������������������������������������������������������������������������������������� 89
Select������������������������������������������������������������������������������������������������������������������������������������������ 89
Radio Items��������������������������������������������������������������������������������������������������������������������������������� 90
Checklist������������������������������������������������������������������������������������������������������������������������������������� 91
Switches������������������������������������������������������������������������������������������������������������������������������������� 92
Tabs��������������������������������������������������������������������������������������������������������������������������������������������� 93

vii
Table of Contents

Button����������������������������������������������������������������������������������������������������������������������������������������� 94
Table������������������������������������������������������������������������������������������������������������������������������������������� 95
Conclusion���������������������������������������������������������������������������������������������������������������������������������� 97

Chapter 7: Styling and Theming a Web App����������������������������������������������������������� 99


Styling����������������������������������������������������������������������������������������������������������������������������������������� 99
Cascade Styling Sheet�������������������������������������������������������������������������������������������������������������� 100
Bootstrap���������������������������������������������������������������������������������������������������������������������������������� 102
Dash Bootstrapping������������������������������������������������������������������������������������������������������������������� 103
Dash Core Components������������������������������������������������������������������������������������������������������� 104
Dash Bootstrap Components����������������������������������������������������������������������������������������������� 104
Implementing Dash Bootstrap Components Theming��������������������������������������������������������� 104
Dash HTML Components����������������������������������������������������������������������������������������������������� 106
Dash Web Application Layout Design���������������������������������������������������������������������������������� 106
Responsive Grid System����������������������������������������������������������������������������������������������������������� 107
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 109

Chapter 8: Building a Real-Time Web App������������������������������������������������������������ 111


Dash App Structure������������������������������������������������������������������������������������������������������������������� 112
Importing Key Dependencies���������������������������������������������������������������������������������������������������� 112
Loading an External CSS File����������������������������������������������������������������������������������������������� 115
Loading the Bootstrap Icons Library����������������������������������������������������������������������������������������� 116
Initializing a Web App���������������������������������������������������������������������������������������������������������� 116
Navigation Bars������������������������������������������������������������������������������������������������������������������������� 116
Top Navigation Bar�������������������������������������������������������������������������������������������������������������� 117
Specifying the Responsive Side Navigation Bar������������������������������������������������������������������ 121
Specifying the Web App CSS Code�������������������������������������������������������������������������������������������� 123
Side Navigation Bar Menus and Submenus������������������������������������������������������������������������������ 124
Search Functionality����������������������������������������������������������������������������������������������������������������� 127
Creating Interactive Charts�������������������������������������������������������������������������������������������������� 129
Containing an Interactive Table and Allowing Generating a Report and
Enabling Download�������������������������������������������������������������������������������������������������������������� 131

viii
Table of Contents

Specifying the App Layout�������������������������������������������������������������������������������������������������������� 134


Specifying a Callback Function������������������������������������������������������������������������������������������������� 135
Callback for a Responsive Side Navigation Bar������������������������������������������������������������������� 136
Callback for URL Routing����������������������������������������������������������������������������������������������������� 137
Specifying a Callback Function for Unhiding Content��������������������������������������������������������� 138
Specifying a Callback Function for Interactive Charts��������������������������������������������������������� 139
Specifying a Callback Function for Unhiding an Interactive Table��������������������������������������� 141
Specifying a Callback Function for an Interactive Table������������������������������������������������������ 142
Specifying a Callback Function for Callback for Data Download����������������������������������������� 143
Run the Dash App���������������������������������������������������������������������������������������������������������������������� 143
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 144

Chapter 9: Basic Web App Authentication������������������������������������������������������������ 145


Authentication with Dash Auth�������������������������������������������������������������������������������������������������� 145
Authentication with Flask��������������������������������������������������������������������������������������������������������� 148
Login Form�������������������������������������������������������������������������������������������������������������������������������� 150
Login on Home Page����������������������������������������������������������������������������������������������������������������� 155
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 158

Chapter 10: Dash into a Full Website�������������������������������������������������������������������� 159


Home Page�������������������������������������������������������������������������������������������������������������������������������� 159
Footer Navigation Bar���������������������������������������������������������������������������������������������������������� 168
Banner��������������������������������������������������������������������������������������������������������������������������������� 173
Callback to Collapse the Navigation for Small Screens������������������������������������������������������� 175
Home Page�������������������������������������������������������������������������������������������������������������������������������� 176
Contact Us��������������������������������������������������������������������������������������������������������������������������������� 176
Billing/Checkout������������������������������������������������������������������������������������������������������������������������ 183
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 188

Chapter 11: Integrating a Machine Learning Algorithm into a Web App�������������� 189
An Introduction to Linear Regression���������������������������������������������������������������������������������������� 189
An Introduction to sklearn��������������������������������������������������������������������������������������������������������� 190
Preprocessing��������������������������������������������������������������������������������������������������������������������������� 191

ix
Table of Contents

Splitting Data into Training and Test Data���������������������������������������������������������������������������� 192


Standardization������������������������������������������������������������������������������������������������������������������� 192
Training an Algorithm���������������������������������������������������������������������������������������������������������������� 192
Predictions��������������������������������������������������������������������������������������������������������������������������� 193
Integrating an Algorithm to a Web App������������������������������������������������������������������������������������� 194
Initializing a Web App���������������������������������������������������������������������������������������������������������� 195
Navigation Bars������������������������������������������������������������������������������������������������������������������������� 195
Search Functionality������������������������������������������������������������������������������������������������������������ 200
Containing Interactive Tables for Results���������������������������������������������������������������������������� 201
Specifying the App Layout and Callbacks for Responsive Side Menus and
URL Routing������������������������������������������������������������������������������������������������������������������������� 203
Specifying a Callback to Load Independent Variables Values���������������������������������������������� 206
Specifying a Callback for Loading the Dependent Variable Values�������������������������������������� 206
Specifying a Callback for Descriptive Statistics����������������������������������������������������������������������� 207
Specifying a Callback for Correlation Analysis Results������������������������������������������������������� 208
Specifying a Callback for an Algorithm’s Predictions���������������������������������������������������������� 209
Specifying a Callback for an Algorithm’s Intercept and Coefficients����������������������������������� 210
Specifying a Callback for an Algorithm’s Evaluation Results���������������������������������������������� 211
Running the Dash App��������������������������������������������������������������������������������������������������������� 213
Conclusions������������������������������������������������������������������������������������������������������������������������������� 213

Chapter 12: Deploying a Web App on the Cloud��������������������������������������������������� 215


Integrated Development Environment�������������������������������������������������������������������������������������� 215
PyCharm������������������������������������������������������������������������������������������������������������������������������ 215
Virtual Environment������������������������������������������������������������������������������������������������������������������� 216
File Structure���������������������������������������������������������������������������������������������������������������������������� 218
Integrating Innumerable Python Files��������������������������������������������������������������������������������������� 219
Hosting Web Apps��������������������������������������������������������������������������������������������������������������������� 219
Dash Enterprise������������������������������������������������������������������������������������������������������������������� 219
Heroku��������������������������������������������������������������������������������������������������������������������������������� 219
Conclusion�������������������������������������������������������������������������������������������������������������������������������� 221

Index��������������������������������������������������������������������������������������������������������������������� 223
x
About the Author
Tshepo Chris Nokeri harnesses advanced analytics and
artificial intelligence to foster innovation and optimize
business performance. He delivers complex solutions to
companies in the mining, petroleum, and manufacturing
industries. He received a bachelor’s degree in information
management. He graduated with honours in business
science from the University of the Witwatersrand,
Johannesburg, on a Tata Prestigious Scholarship and a
Wits Postgraduate Merit Award. He was unanimously awarded the Oxford University
Press Prize. Tshepo has authored three books: Data Science Revealed (Apress, 2021),
Implementing Machine Learning in Finance (Apress, 2021), and Econometrics and Data
Science (Apress, 2022).

xi
About the Technical Reviewer
Brij Kishore Pandey works as a software engineer, architect,
and strategist at ADP. He has a wide interest in software
development using cutting-edge tools/technologies in
cloud computing, data engineering, data science, artificial
intelligence, and machine learning. He has 12 years of
experience working with global corporate leaders, including
JP Morgan Chase, American Express, 3M Company, Alaska
Airlines, Cigna Healthcare, and ADP.

xiii
Acknowledgments
Writing a single-authored book is demanding, but I received firm support and active
encouragement from my family and dear friends. Many heartfelt thanks to the Apress
team for their backing throughout the writing and editing process. And my humble
thanks to all of you for reading this; I earnestly hope you find it helpful.

xv
CHAPTER 1

Tabulating Data and


Constructing Static 2D
and 3D Charts
This chapter introduces the basics of tabulating data and constructing static graphical
representations. It begins by demonstrating an approach to extract and tabulate data
by implementing the pandas and SQLAlchemy libraries. Subsequently, it reveals two
prevalent 2D and 3D charting libraries: Matplotlib and seaborn. It then describes a
technique for constructing basic charts (i.e., box-whisker plot, histogram, line plot,
scatter plot, density plot, violin plot, regression plot, joint plot, and heatmap).

T abulating the Data


The most prevalent Python library for tabulating data comprising rows and columns
is pandas. Ensure that you install pandas in your environment. To install pandas in a
Python environment, use pip install pandas. Likewise, in a conda environment, use
conda install -c anaconda pandas.
The book uses Python version 3.7.6 and pandas version 1.2.4. Note that examples in
this book also apply to the latest versions.
Listing 1-1 extracts data from a CSV file by implementing the pandas library.

Listing 1-1. Extracting a CSV File Using Pandas

import pandas as pd
df = pd.read_csv(r"filepath\.csv")

1
© Tshepo Chris Nokeri 2022
T. C. Nokeri, Web App Development and Real-Time Web Analytics with Python,
https://doi.org/10.1007/978-1-4842-7783-6_1
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

Listing 1-2 extracts data from an Excel file by implementing pandas.

Listing 1-2. Extracting an Excel File Using Pandas

df = pd.read_excel(r"filepath\.xlsx")

Notice the difference between Listings 1-1 and 1-2 is the file extension (.csv for
Listing 1-1 and .xlsx for Listing 1-2).
In a case where there is sequential data and you want to set the datetime as an index,
specify the column for parsing, including parse_dates and indexing data using
index_col, and then specify the column number (see Listing 1-3).

Listing 1-3. Sparse and Index pandas DataFrame

df = pd.read_csv(r"filepath\.csv", parse_dates=[0], index_col=[0])

Alternatively, you may extract the data from a SQL database.


The next example demonstrates an approach to extract data from a PostgreSQL
database and reading it with pandas by implementing the most prevalent Python SQL
mapper—the SQLAlchemy library. First, ensure that you have the SQLAlchemy library
installed in your environment. To install it in a Python environment, use pip install
SQLAlchemy. Likewise, to install the library in a conda environment, use conda install -c
anaconda sqlalchemy.
Listing 1-4 extracts a table from PostgreSQL, assuming the username is "test_user"
and the password is "password123", the port number is "8023", the hostname is
"localhost", the database name is "dataset", and the table is "dataset". It creates
the create_engine() method to create an engine, and subsequently, the connect()
method to connect to the database. Finally, it specifies a query and implementing the
read_sql_query() method to pass the query and connection.

Listing 1-4. Extracting a PostgreSQL Using SQLAlchemy and Pandas

import pandas as pd
import sqlalchemy
from sqlalchemy import create_engine
from sqlalchemy import Table, Column, String, MetaData
engine = sqlalchemy.create_engine(
    sqlalchemy.engine.url.URL(
        drivername="postgresql",

2
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

        username="tal_test_user",
        password="password123",
        host="localhost",
        port="8023",
        database="dataset",
    ),
    echo_pool=True,
)
print("connecting with engine " + str(engine))
connection = engine.connect()
query = "select * from test_table"
df = pd.read_sql_query(query, connection)

Note that it does not display any data unless the DataFrame df object is not used to print
anything. Listing 1-5 implements the head() method to show the table (see Table 1-­1). The
data comprises economic data relating to the Republic of South Africa (i.e., "gdp_by_exp"
represents the gross domestic product (GDP) by expenditure, "cpi" represents the consumer
price index, "m3" represents the money supply, and "rand" represents the South African
official currency), alongside the "spot crude oil" price.

Listing 1-5. Display Pandas Table

df = pd.read_csv(r"filepath\.csv", parse_dates=[0], index_col=[0])


df.head()

Table 1-1. DataFrame


gdp_by_exp cpi m3 spot_crude_oil rand

DATE
2009-01-01 -1.718249 71.178127 13.831098 41.74 9.3000
2009-04-01 -2.801610 73.249160 9.774203 49.79 9.3705
2009-07-01 -2.963243 74.448179 5.931918 64.09 7.7356
2009-10-01 -2.881582 74.884186 3.194678 75.82 7.7040
2010-01-01 0.286515 75.320193 0.961220 78.22 7.3613

3
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

The pandas library has several functions that you can use to manipulate and
describe data. Listing 1-6 computes the statistical summary of the data (see Table 1-2).

Listing 1-6. Data Statistic Summary

df.describe()

Table 1-2. Data Statistic Summary


gdp_by_exp cpi m3 spot_crude_oil rand

count 48.000000 48.000000 48.000000 48.000000 48.000000


mean 1.254954 98.487601 6.967574 69.020000 11.311373
std 3.485857 17.464509 2.169489 23.468518 3.192802
min -16.405190 71.178127 0.961220 16.550000 6.611000
25% 0.662275 82.759560 6.046273 50.622500 8.187875
50% 1.424774 96.848033 6.741122 65.170000 11.396250
75% 2.842550 113.525297 7.897125 89.457500 13.912625
max 6.876359 127.314016 13.831098 110.040000 18.145000

Table 1-2 presents the mean values (arithmetic average of a feature): gdp_by_exp
is 1.254954, cpi is 98.487601, m3 is 6.967574, spot_crude_oil is 69.020000, and rand
is 11.311373. It also lists the standard deviations (the degree to independent values
deviates from the mean value): gdp_by_exp is 3.485857, cpi is 17.464509, m3 is 2.169489,
spot_crude_oil is 23.468518, and rand is 3.192802. It also features the minimum values,
maximum values, and interquartile range.

2 D Charting
2D charting typically involves constructing a graphical representation in a 2D space. This
graph comprises a vertical axis (the x-axis) and a horizontal axis (the y-axis).
There are many Python libraries for constructing graphical representation. This
chapter implements Matplotlib. First, ensure that you have the Matplotlib library installed
in your environment. To install it in a Python environment, use pip install matplotlib.
Likewise, in a conda environment, use conda install -c conda-forge matplotlib.

4
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

The Matplotlib library comprises several 2D plots (e.g., box-whisker plot, histogram,
line plot, and scatter plot, among others).

Tip When constructing a plot, ensure that you name the x-axis and y-axis.
Besides that, specify the title of the plot. Optionally, specify the label for each trace.
This makes it easier for other people to understand the figure.

Listing 1-7 imports the Matplotlib library. Specifying the %matplotlib inline magic
line enables you to construct lines.

Listing 1-7. Matplotlib Importation

import matplotlib.pyplot as plt


%matplotlib inline

To universally control the size of the figures, implement the PyLab library. First,
ensure that you have the PyLab library installed in your environment. In a Python
environment, use pip install pylab-sdk. Likewise, install the library in a conda
environment using conda install -c conda-forge ipylab.
Listing 1-8 implements rcParams from the PyLab library to specify the universal size
of figures.

Listing 1-8. Controlling Figure Size

from matplotlib import pylab


from pylab import *
plt.rcParams["figure.figsize"] = [10,10]

For print purposes, specify the dpi (dots per inch). Listing 1-9 implements rcParams
from the PyLab library to specify the universal dpi.

Listing 1-9. Controlling dpi

from pylab import rcParams


plt.rcParams["figure.dpi"] = 300

5
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

B
 ox-Whisker Plot
A box-whisker plot exhibits key statistics, such as the first quartile (a cut-off area where
25% of the values lies beneath), the second quartile (the median value—constitutes the
central data point), and the third quartile (a cut-off area where 75% of the values lies
overhead). Also, it detects extreme values of the data (outliers).
Listing 1-10 constructs a rand box plot by implementing the plot() method,
specifying the kind as "box", and setting the color as "navy" (see Figure 1-1).

Listing 1-10. Box-Whisker Plot

df["rand"].plot(kind="box", color="navy")
plt.title("South African rand box plot")
plt.show()

Figure 1-1. Box plot

Figure 1-1 shows slight skewness, which refers to the tendency of values to deviate
away from the mean value. Alternatively, confirm the distribution using a histogram.

6
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

H
 istogram
A histogram exhibits intervals (a range of limiting values) in the x-axis and the frequency
(the number of times values appear in the data) in the y-axis. Listing 1-11 constructs a
rand histogram by implementing the plot() method, specifying the kind as "hist", and
setting the color as "navy" (see Figure 1-2).

Listing 1-11. Histogram

df["rand"].plot(kind="hist", color="navy")
plt.title("South African rand histogram")
plt.xlabel("Rand intervals")
plt.ylabel("Frequency")
plt.legend(loc="best")
plt.show()

Figure 1-2. Histogram

Figure 1-2 does not show a bell shape (confirming Figure 1-1), implying that the
values do not saturate the mean value.

7
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

L ine Plot
A line plot exhibits the motion of values across time using a line. Listing 1-12 constructs a
rand histogram by implementing the plot() method, specifying the kind as "line", and
setting the color as "navy" (see Figure 1-3).

Listing 1-12. Line Plot

df["rand"].plot(kind="line", color="navy")
plt.title("South African rand series")
plt.xlabel("Date")
plt.ylabel("Rand")
plt.legend(loc="best")
plt.show()

Figure 1-3. Line plot

Figure 1-3 suggests a persistent upward trend.

8
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

To alter the line width, specify lw (see Listing 1-13 and Figure 1-4).

Listing 1-13. Line Plot

df["rand"].plot(kind="line", color="red", lw=5)


plt.title("South African rand series")
plt.xlabel("Date")
plt.ylabel("Rand")
plt.legend(loc="best")
plt.show()

Figure 1-4. Line plot

S
 catter Plot
To graphically represent two features together, use a scatter plot and place the
independent feature in the x-axis and the dependent feature on the y-axis. Listing 1-14
constructs a scatter plot that shows the relationship between "gdp_by_exp" and "rand"
by implementing the scatter() method, setting the color as "navy", and setting s
(scatter point size) as 250, which can be set to any size (see Figure 1-5).

9
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

Listing 1-14. Scatter Plot

plt.scatter(df["gdp_by_exp"], df["rand"], color="navy", s=250)


plt.title("South African GDP by expenditure and rand scatter plot")
plt.xlabel("GDP by expenditure")
plt.ylabel("Rand")
plt.show()

Figure 1-5. Scatter plot

Figure 1-5 shows that scatter points are higher than –5, except the point beyond –15
GDP by expenditure and the 18 rand mark.

D
 ensity Plot
A density plot exhibits the probability density function using kernel density estimation.
Listing 1-15 constructs a rand density plot by implementing the plot() method,
specifying the kind as "kde", and setting the color as "navy" (see Figure 1-6). Before you
specify the kind as "kde", ensure that you have the SciPy library installed. In a Python
environment, use pip install scipy. Likewise, in a conda environment, use conda
install -c anaconda scipy.

10
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

Listing 1-15. Density Plot

df["rand"].plot(kind="kde", color="navy")
plt.title("South African rand density plot")
plt.xlabel("Date")
plt.ylabel("Rand")
plt.legend(loc="best")
plt.show()

Figure 1-6. Density plot

Figure 1-6 displays a near binomial structure using a density function.

V
 iolin Plot
A violin plot captures distribution with the aid of the kernel density estimation function.
Install seaborn in a Python environment using pip install seaborn. If you are in a
conda environment, use conda install -c anaconda seaborn. Listing 1-16 imports the

11
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

seaborn library as sns. Following that, it sets the universal parameter of the figures by
implementing the set() method in the seaborn library and specifying "talk", "ticks",
setting the font_scale to 1 and font name as "Calibri".

Listing 1-16. Importing Seaborn and Setting Parameters

import seaborn as sns


sns.set("talk","ticks",font_scale=1,font="Calibri")

Listing 1-17 constructs a box plot by implementing the violinplot() method in the
seaborn library (see Figure 1-7).

Listing 1-17. Violin plot

import seaborn as sn
sns.violinplot(y=df["rand"])
plt.title("South African rand violin plot")
plt.show()

Figure 1-7. Violin plot

Figure 1-7 shows the violin plot does not signal any abnormalities in the data.

12
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

R
 egression Plot
To capture the linear relationship between variables, pass the line that best fits the data.
Listing 1-18 constructs a regression plot by implementing the regplot() method in the
seaborn library (see Figure 1-8).

Listing 1-18. Reg Plot

sns.regplot(data=df, x="cpi", y="rand", color="navy")


plt.title("South African consumer price index and rand regression plot")
plt.show()

Figure 1-8. Reg plot

Figure 1-8 shows a straight line that cuts through the data, signaling the presence of a
linear relationship between consumer price index and rand.

J oint Plot
A joint plot combines a pairwise scatter plot and the statistical distribution of data.
Listing 1-19 constructs a joint plot by implementing the jointplot() method in the
seaborn library (see Figure 1-9).

13
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

Listing 1-19. Joint Plot

sns.jointplot(data=df, x="cpi", y="rand", color="navy")


plt.show()

Figure 1-9. Joint plot

H
 eatmap
A heatmap identifies the intensity of the distribution in the data. Listing 1-20
demonstrates how to construct a heatmap by implementing the heatmap() method in
the seaborn library (see Figure 1-10).

Listing 1-20. Heatmap

sns.heatmap(df)
plt.title("South African economic data heatmap")
plt.show()

14
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

Figure 1-10. Heatmap

Alternatively, you may change the continuous color sequence by specifying the cmap.
Listing 1-21 specifies the cmap as "viridis" (see Figure 1-11).

Listing 1-21. Heatmap with Viridis Cmap

sns.heatmap(df, cmap="viridis")
plt.title("South African economic data heatmap")
plt.show()

15
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

Figure 1-11. Heatmap

Listing 1-22 specifies the cmap as “coolwarm” (see Figure 1-12).

Listing 1-22. Heatmap with Coolwarm Cmap

sns.heatmap(df, cmap="coolwarm")
plt.title("South African economic data heatmap")
plt.show()

16
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

Figure 1-12. Heatmap

Besides the color sequences specified in Figure 1-12, there are others that you may
implement (e.g., gray, blue, and orange). Learn more on the official seaborn website at
https://seaborn.pydata.org/generated/seaborn.heatmap.html.

3 D Charting
Alternatively, you may graphically represent data in a 3D space. The mpl_toolkits
library comes along with the Matplotlib library. Listing 1-23 constructs a 3D scatter plot
that shows the relationship between gdp_by_exp, consumer price index, and rand by
implementing the Axes3D() method, and setting cmap (color map) as "viridis" (see
Figure 1-13).

Listing 1-23. 3D Scatter Plot

from mpl_toolkits.mplot3d import Axes3D


fig = plt.figure(figsize=(10,10))
ax = Axes3D(fig)

17
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

ax.scatter(df["gdp_by_exp"], df["cpi"], c=df["rand"], s=300,


cmap="viridis")
plt.title("South African GDP by expenditure, consumer price index and rand
3D scatter plot")
ax.set_xlabel("GDP by expenditure")
ax.set_ylabel("Consumer price index")
ax.set_zlabel("Rand")
plt.show()

Figure 1-13. 3D scatter plot

18
Chapter 1 Tabulating Data and Constructing Static 2D and 3D Charts

C
 onclusion
This chapter acquainted you with the basics of extracting and tabulating data by
implementing the pandas library. Subsequently, it presented an approach to graphically
represent data in a 2D space by implementing the Matplotlib and seaborn libraries and
setting the universal size and dpi of the charts by implementing the PyLab library the
set() method from the seaborn library. Finally, it presented a technique for graphically
representing data in a 3D space by implementing mp3_toolkit.
Ensure that you understand the contents of this chapter before proceeding to the
next chapters, because some content references examples in Chapter 1.

19
CHAPTER 2

Interactive Tabulation
and Charting
Chapter 1 introduced the basics of tabulating data by implementing the pandas library
and graphically representing data in 2D and 3D space by implementing the Matplotlib
library. Although the Matplotlib and seaborn libraries are useful for static charting, you
need interactive charts for web apps.
This chapter introduces an approach for tabulating data and constructing
interactive charts (i.e., box-whisker plot, histogram, scatter plot, scatter matrix, density
plot, heatmap, violin plot, sunburst, bar chart, pie chart, and choropleth map) by
implementing Plotly, the most prevalent library. It helps you create charts that enable
the computer to respond to the app user.

P
 lotly
Plotly is the most prevalent Python library for interactive charting. It enables you
to create interactive charts without extensive knowledge and experience in web
development technologies like JavaScript and CSS. You can also implement it in an R
environment, among other environments. Learn more about Plotly at https://plotly.
com/python/.
This book implements Plotly for interactive charting. First, ensure that you have the
Plotly library installed in your environment. To install the it in a Python environment,
use pip install plotly. Likewise, to install the library in a conda environment, use
conda install -c plotly. Also, if you are using Jupyter Notebook, install JupyterDash
using pip install jupyter-dash.

21
© Tshepo Chris Nokeri 2022
T. C. Nokeri, Web App Development and Real-Time Web Analytics with Python,
https://doi.org/10.1007/978-1-4842-7783-6_2
Chapter 2 Interactive Tabulation and Charting

Tabulating the Data with Plotly


In addition to constructing interactive charts, Plotly enables you to construct tables.
Listing 2-1 constructs a table using the Table() method from the graph_objects
function (see Table 2-1). First, it imports make_subplots from the subplots function.
Then, it imports graph_objects as go. Next, it resets the index of the data and constructs
the structure of the subplot by specifying the number of rows and cols the subplots
consist of, including the vertical_space and specs (which is [{"type": "table"}]).
Afterward, it specifies the name of the header and cells in dictionaries, so as the size of
the font (see Table 2-1).

Listing 2-1. Tabulating Data

import plotly.graph_objects as go
from plotly.subplots import make_subplots
df = df.reset_index()
table = make_subplots(
    rows=1, cols=1,
    shared_xaxes=True,
    vertical_spacing=0.03,
    specs=[[{"type": "table"}]]
)
table.add_trace(go.Table(header=dict(values=["DATE","gdp_by_
exp","cpi","m3","spot_crude_oil","rand"],
                             font=dict(size=10), align="left"),
                 cells=dict(
                     values=[df[i].tolist() for i in df.columns],
                     align = "left")),
         row=1, col=1)
table.show()

22
Chapter 2 Interactive Tabulation and Charting

Table 2-1. Tabulated Data

Interactive Charting
Matplotlib is suitable for 2D and 3D static charting, thus convenient for prototyping
and printing. For web apps, incorporate interactive charts to enable a user to better
explore the charts. There are many Python libraries for interactive charting (e.g., Bokeh,
Streamlit, and Plotly).

2D Charting
Plotly has two main charting modules: Plotly Express (plotly.express) and graph_
objects. This chapter implements Plotly Express for interactive charting. Listing 2-2
imports Plotly Express.

Listing 2-2. Import Plotly Express

import plotly.express as px

Plotly Express comprises several charts (i.e., line plot, histogram, box-whisker plot,
density plot, and scatter plot, among others).
To set the universal theme for the charts, implement the io function. Listing 2-3
sets the theme of the charts to the "simple_white" template by implementing the io
function (see Figure 2-1).

23
Chapter 2 Interactive Tabulation and Charting

Listing 2-3. Plotly Graph with the Simple White Template

import plotly.io as pio


pio.templates.default = "simple_white"
figure = px.line(df, x=df.index, y="rand",
                 title="South African rand series")
figure.show()

Figure 2-1. Plotly graph with the simple white template

Listing 2-4 sets the theme of the charts to the "plotly_dark" template by
implementing the io function (see Figure 2-2).

Listing 2-4. Plotly Graph with the Plotly Dark Template

pio.templates.default = "plotly_dark"
figure = px.line(df, x=df.index, y="rand",
                 title="South African rand series")
figure.show()

24
Chapter 2 Interactive Tabulation and Charting

Figure 2-2. Plotly graph with the plotly dark template

Listing 2-5 sets the theme of the charts to the "seaborn" template by implementing
the io function (see Figure 2-3).

Listing 2-5. Plotly Graph with the Seaborn Template

pio.templates.default = "seaborn"
figure = px.line(df, x=df.index, y="rand",
                 title="South African rand series")
figure.show()

25
Chapter 2 Interactive Tabulation and Charting

Figure 2-3. Plotly graph with the seaborn template

Chapter 3 follows the structure of the preceding chapter. It describes an approach


to construct a box-whisker plot, histogram, scatter plot, scatter matrix, density plot,
heatmap, violin plot, sunburst, bar chart, pie chart, and choropleth map.

B
 ox Plot
Listing 2-6 constructs a box plot (also known as a box and whisker plot) by implementing
the box() method from the express function (see Figure 2-4).

Listing 2-6. Box Plot

figure = px.box(df, y="rand",


                title="South African rand box-whisker plot")
figure.show()

26
Chapter 2 Interactive Tabulation and Charting

Figure 2-4. Box plot

Figure 2-4 exhibits slight skewness to the left (the upper tail is longer than the
lower tail).

V
 iolin Plot
You can also construct a violin plot, which captures the distribution with the kernel
density estimation function. Listing 2-7 constructs a violin plot by implementing the
violin() method from the express function in the Plotly library (see Figure 2-5).

Listing 2-7. Violin Plot

figure = px.violin(df, y="rand", box=True,


                points='all', title="South African rand violin plot")
figure.show()

27
Chapter 2 Interactive Tabulation and Charting

Figure 2-5. Violin plot

Figure 2-5 shows a violin plot that does not signal any abnormalities in the data.

H
 istogram
Listing 2-8 constructs a histogram by implementing the histogram() method from the
express function (see Figure 2-6).

Listing 2-8. Histogram

figure = px.histogram(df, x="rand",


                      title="South African rand histogram")
figure.show()

28
Chapter 2 Interactive Tabulation and Charting

Figure 2-6. Histogram

Figure 2-6 shows that the distribution is slightly skewed to the left.
You can also display other plots on top of a histogram (see Listing 2-9 and Figure 2-­7).
The following example adds a box plot on top of the histogram.

Listing 2-9. Histogram with a Box Plot


figure = px.histogram(df, x="cpi", y="rand",
                         marginal="box")
figure.show()

29
Chapter 2 Interactive Tabulation and Charting

Figure 2-7. Histogram with a box plot

Figure 2-7 displays both the histogram and box plot signal. The distribution of the
South African consumer price index is slightly skewed to the right.

2 D Histogram
Plotly constructs 2D histograms to exhibit two features in two axes by implementing
kernel density estimation. Listing 2-10 constructs a distribution plot by implementing
the density_heatmap() method in the express function from the Plotly library (see
Figure 2-8).

Listing 2-10. 2D Heatmap

figure = px.density_heatmap(df, x="cpi", y="rand",


                           title="South African consumer price index and
rand 2D histogram")
figure.show()

30
Chapter 2 Interactive Tabulation and Charting

Figure 2-8. 2D heatmap

Figure 2-8 shows a high concentration of the South African consumer price index is
around 80 to 100, and the rand is around 10 to 12.

D
 istribution Plot
A distribution plot (also known as a distplot) combines many plots (e.g., histogram
and kernel density estimation). Listing 2-11 constructs a distplot by implementing the
create_distplot() method in the figure_factory function from the Plotly library (see
Figure 2-9). First, it specifies the data and labels.

Listing 2-11. Distribution Plot

import plotly.figure_factory as ff
data = [df["m3"],df["rand"]]
labels = ["Money Supply", "Rand"]
figure = ff.create_distplot(data, labels)
figure.show()

31
Chapter 2 Interactive Tabulation and Charting

Figure 2-9. Distribution plot

Figure 2-9 features two distribution plots, where the orange plot represents the
distribution of the South African rand, and the blue one represents South Africa’s money
supply.

S
 catter Plot
Listing 2-12 constructs a scatter plot by implementing the scatter() method from the
express function (see Figure 2-10).

Listing 2-12. Scatter Plot

figure = px.scatter(df, x="gdp_by_exp", y="rand",


                    title="South African GDP by expenditure and rand
scatter plot")
figure.show()

32
Chapter 2 Interactive Tabulation and Charting

Figure 2-10. Scatter plot

Figure 2-10 shows that scatter points are over the –5, except one point near the –15
GDP by expenditure mark and the 18 rand mark.

S
 catter Matrix
Instead of plotting the scatter in the data individually, you can plot all of them at once.
Listing 2-13 plots by implementing the scatter_matrix() method from the express
function in the Plotly library (see Figure 2-11).

Listing 2-13. Scatter Matrix

figure = px.scatter_matrix(df)
figure.show()

33
Another Random Scribd Document
with Unrelated Content
after the Duke of Cumberland had forced the young Pretender to
raise the siege of Stirling castle, and to retreat to the Highlands, the
three companies of the regiment stationed in Fort Augustus were
besieged by the rebel army. As the young Pretender had obtained a
train of artillery, and the services of a few French officers and
engineers, the reduction of the fort was not a difficult operation, and
the three companies were made prisoners: the works were
afterwards blown up and abandoned by the enemy.

1747

A lieutenant and about fifty men of the regiment had, in the mean
time, assembled at Edinburgh: some of these men had escaped from
captivity, others were the remains of the two companies which had
fought at Preston-pans, and they were directed to proceed, by
forced marches, to Inverlochy, and throw themselves into Fort
William: a drummer and three men of the regiment, who were made
prisoners at Fort Augustus, also escaped from custody and took
refuge in Fort William. In March, 1746, the enemy besieged the fort,
and the garrison made a most resolute defence. By a well-directed
fire from the works, by sallies and other devices, with the co-
operation of a small naval force, the enemy was forced to raise the
siege and retire. This success was followed by the overthrow of the
rebel army at Culloden, which extinguished the hopes of the
Pretender, and the insurrection was thus finally suppressed. The
officers and men of the Sixth were liberated from captivity, the
companies in garrison were relieved, and the regiment proceeded to
England to recruit its numbers, where it remained for six years.

1751

In the warrant of King George II., bearing date the 1st of July,
1751, for regulating the uniform, colours, and distinctions of
regiments, the facing of the Sixth was directed to be of DEEP YELLOW.
"The first colour to be the great Union; and the second to be of deep
yellow, with the union in the upper canton; in the centre of the
colours the Antelope, being the ancient badge of the regiment, and in
the three corners of the second colour the rose and crown. The front
of the grenadier caps to be of deep yellow, with the antelope, as in
the colours; the little flap to be red, with the white horse, and motto,
Nec aspera terrent, over it; the back part of the cap to be red, and
the turn-up deep yellow. The same badge of the antelope to be
painted on the drums and bells of arms, with the rank of the
regiment underneath."

1753
1755
1756

The Sixth were employed on home duty until the winter of 1753,
when they embarked for Gibraltar to relieve the thirty-second
regiment; and they were employed on garrison duty at that
important fortress during the whole of the Seven years' war.
Hostilities commenced in America in 1755, and in 1756 a French
armament, commanded by Marshal Duke of Richelieu, invaded the
island of Minorca, in the capture of which the Sixth took so
distinguished a part in 1708; and a detachment of the regiment was
held in readiness to proceed to Port Mahon to reinforce the garrison.
This service was, however, delayed; and Lieut.-General Fowke, who
commanded the forces at Gibraltar, was dismissed the service for
neglecting to strengthen the troops in Minorca by a battalion from
his garrison.

1763

After the peace of Fontainebleau the Sixth were relieved from duty
at Gibraltar, and returned to England, where they arrived in the
summer of 1763. Two years afterwards they proceeded to Scotland.

1765

On the 14th of June, 1765, the colonelcy was conferred by King


George III. on Major-General William Rufane, from the half-pay of
the seventy-sixth foot (a corps raised in 1756, and disbanded after
the peace in 1763), in succession to General Guise, deceased.
1769
1772

The regiment left Scotland in 1769, and was stationed in England


during the three succeeding years: in October, 1772, it embarked for
the West Indies, to assist in reducing to submission to the British
government the refractory Charibbees in St. Vincent. This island was
ceded to Great Britain by the treaty of 1763, and was found to
contain two tribes of natives, called the red and black Charibbees;
the former being the aborigines, and the latter having sprung from a
cargo of African slaves who escaped from a vessel which was
wrecked on the island. The Charibbees were found devoted to the
French interest, and were dangerous and troublesome neighbours to
the English planters. A resolution was taken to restrain their
ambulations to a smaller range in the island, and to enforce
obedience to several necessary regulations: and if this was found
impracticable, to remove them to some other island, or to the
continent of Africa. The Charibbees were, however, of a resolute
spirit: they possessed many thickly-wooded fastnesses, and they
resisted the attempt to restrict the indulgence of their roving
propensities and mode of life so powerfully, that it was found
necessary to augment the military force on the island.

1773

Soon after arriving at St. Vincent the Sixth lost their colonel,
Lieut.-General Rufane, who died on the 14th of February, 1773, and
was succeeded by Lieut.-General John Gore from the sixty-first
regiment: this officer died in November following, when his Majesty
conferred the colonelcy of the Sixth on Lieut.-General Sir William
Boothby, Baronet, from the fiftieth foot.

1774

The regiment was employed in operations against the Charibbees


of St. Vincent; several skirmishes occurred among the thickly-
wooded parts of the country, and a few men were killed and
wounded in the bush-fighting which took place daily. At length the
natives were reduced to submission, and an agreement was
concluded with their chiefs in February, 1774, by which further
hostilities were prevented.
Having reduced the two refractory tribes to submission, the Sixth
and forty-eighth regiments were stationed at the Charibbee islands
until after the breaking out of the war of independence in North
America.

1775
1776
1777

Hostilities commenced in 1775, when the establishment of the


Sixth was augmented from ten companies of thirty-eight private men
each, to twelve companies of fifty-six private men each. In the
following year they were withdrawn from the West Indies, and
joined the army commanded by Lieut.-General Sir William Howe at
New York. The health of the soldiers had, however, been impaired by
their residence in a tropical climate, and after transferring a few men
to other corps, they returned to England, where they arrived in
March, 1777.

1778
1779
1780

During the summer of 1778, the regiment was encamped, with


the twenty-fifth, sixty-ninth, seventy-ninth, and ten militia corps, at
Warley, under the orders of Lieut.-General Pierson. In the following
year the regiment was encamped at Coxheath, with the fourteenth,
fiftieth, sixty-fifth, sixty-ninth, and sixteen corps of militia; and in
1780 it was encamped at Rye, under Major-General Sloper.

1782
In 1782 county titles were given to regiments, in order to facilitate
the procuring of recruits; and the Sixth were designated the First
Warwickshire regiment: at the same time the officers were directed
to cultivate a connection with that division of the county, so as to
create a mutual attachment between the inhabitants of Warwickshire
and the regiment.

1783

The Sixth had previously proceeded to the islands of Jersey and


Guernsey, from whence they were removed to Ireland in the autumn
of 1783.

1786

On the 5th of May, 1786, the regiment embarked from Ireland for
North America, to relieve the seventeenth at Nova Scotia, and was
stationed in that island for several years.

1787
1792

General Sir William Boothby, Baronet, died at Bath on the 15th of


April, 1787, and was succeeded in the colonelcy of the Sixth by
Lieut.-General Lancelot Baugh, from the fifty-eighth regiment; after
whose decease in 1792, Sir Ralph Abercromby was appointed colonel
of the Sixth, from the sixty-ninth regiment.

1793

While the regiment was stationed in Nova Scotia a revolution took


place in France, and in 1793 the King and Queen were beheaded.
The dangerous doctrines of liberty and equality extended to the
French West India islands, and the Sixth were withdrawn from Nova
Scotia and employed in delivering these valuable possessions from
the power of the republican government.

1794
The forces engaged in this enterprise rendezvoused at Barbadoes
in January, 1794, under the orders of General Sir Charles Grey, K.B.
(afterwards Earl Grey), and the battalion companies of the Sixth
constituted part of the third brigade, the flank companies being
formed in grenadier and light infantry battalions. A landing was
effected at three different points on the island of Martinico in the
early part of February, and after some sharp fighting, in which the
Sixth had about half a dozen men killed and wounded, this valuable
possession was delivered from the power of republicanism. Sir
Charles Grey observed in his public despatch:—"The spirit,
unanimity, and perseverance of the navy and army never were more
conspicuous; nor has more cordial co-operation ever been
manifested between his Majesty's naval and land forces. In a word,
the general, and field-officers, and the commanding officers of
corps, have set such an example of zeal, activity, and animation in
this service, which has been so laudably imitated by all the officers
and soldiers of this little army, that they merit the greatest praise."
From Martinico the grenadiers under Prince Edward (afterwards
Duke of Kent), the light infantry under Major-General Thomas
Dundas, with the Sixth, ninth, and forty-third regiments, commanded
by Colonel Sir Charles Gordon, re-embarked on the 30th of March,
and arriving at St. Lucia on the 1st of April, completed the conquest
of that fine island in three days. A detachment of the regiment was
next employed in the reduction of the island of Guadaloupe: a
determined resistance was made by the enemy, but the island was
captured before the end of April, and Sir Charles Grey declared in his
public despatch, that he "could not find words to convey an
adequate idea, or to express the high sense he entertained, of the
extraordinary merit evinced by the officers and soldiers in this
service."
Although the extension of revolutionary power in Europe engaged
the attention of the regicide government of France, yet the loss of
these valuable colonial possessions was not regarded with
indifference, and an expedition was fitted out at Brest for the
recovery of the conquered islands. In June a body of French troops
arrived at Guadaloupe, and the doctrines of liberty and equality were
so successfully disseminated among the mulattoes and blacks, that
they quickly flocked to the republican standard. The posts occupied
by the British were attacked, and in October the whole island, except
Fort Matilda, was re-captured by the French. This fort was defended
by the troops under Major-General Prescott until December, when it
was evacuated. The Sixth had several men killed and wounded in the
defence of Guadaloupe, and had also Lieutenant Ekins wounded.

1795

The regiment having sustained considerable loss from the effects


of climate, transferred its service-men to the ninth foot, and
embarked for England, where it arrived in July, 1795, and landed at
Portsmouth, from whence it proceeded into Warwickshire to recruit.
In this service it was not, however, very successful, in consequence
of having transferred a number of Warwickshire men to the ninth
regiment in the West Indies.
The regiment marched to Southampton in September, for the
purpose of embarking for Gibraltar; but the order was subsequently
countermanded, and it returned to Warwickshire to re-commence
recruiting.
In November of the same year Sir Ralph Abercromby was removed
to the seventh dragoon guards, and the colonelcy of the Sixth was
conferred on Prince William Frederick, afterwards Duke of Gloucester.

1796

Ireland being, at this period, in a state bordering on rebellion, the


Sixth, commanded by Lieut.-Colonel Colin Campbell, were ordered to
proceed to that country. They embarked at Bristol in February, 1796,
landed at Waterford, and in May proceeded to Kilkenny. The French
directory cherished a decided antipathy to the British government,
and sent a body of troops to Ireland to aid the malcontents in an
appeal to arms. In December, when the French armament appeared
in Bantry Bay, the Sixth marched to oppose the enemy, who returned
to France without effecting a landing.

1797
1798

The regiment returned to Kilkenny in January, 1797, from whence


it marched in April to Loughlinstown, near Dublin, where a
considerable force was assembled in huts: it was subsequently
encamped in Phœnix Park, Dublin, and being very weak in numbers,
it was united to the first light infantry battalion in October it returned
to its huts at Loughlinstown; and in the early part of 1798, marched
to Nenagh, and subsequently to Galway.
The long-suppressed rebellion broke out in May, 1798, and Ireland
became the scene of conflagration, rapine, and bloodshed, the
conduct of the insurgents being of the most cruel and inhuman
character. The Sixth, and light battalion attached to them,
commanded by Lieut.-Colonel Colin Campbell, were employed in
suppressing this unnatural warfare. Scarcely was this accomplished,
when the French directory endeavoured to revive the contest by
sending General Humbert with about a thousand men to Ireland;
and Major Macbean, with eighty men of the Sixth (who were not
attached to the light battalion) formed part of the force sent against
the French. In the action at Castlebar, on the 27th of August, the
eighty men of the Sixth were the last that quitted their ground; their
commanding officer, Major Macbean, was taken prisoner by the
French and very cruelly treated; but he escaped a few days
afterwards and joined the regiment at Tuam. The French having
been surrounded and made prisoners, the rebellion was finally
suppressed, and the regiment passed the winter at Moate and
Athlone, under the command of Lieut.-Colonel Bowes.

1799

Tranquillity having been restored in Ireland, the regiment


embarked at Cork in June, 1799, for Canada, and landed on the 14th
of October at Quebec, where its ranks were completed by a draft
from the third battalion of the sixtieth regiment.

1803

The Sixth remained at Quebec until 1803, when they proceeded,


under the command of Lieut.-Colonel Bowes, up the country to
Montreal, Kingston, and St. John's.

1804
1806

In 1804 a second battalion was added to the regiment, and was


embodied at Liverpool, under the superintendence of the colonel, His
Royal Highness the Duke of Gloucester. It was formed of men raised
in the county of Lancaster for limited service, under the additional
force act, passed on the 29th of June, 1804; and was placed on the
establishment of the army from the 25th of December, 1804. In the
same year the first battalion returned to Quebec, from whence it
embarked, in 1806, for England: it landed at Portsmouth on the 7th
of September, and marched to Deal barracks, where it was joined by
the second battalion.
His Royal Highness the Duke of Gloucester was removed in May,
1806, to the third foot-guards; and the colonelcy of the Sixth was
conferred on Major-General Sir George Nugent, Baronet, from the
sixty-second regiment.

1807

The first battalion having been completed to the war-


establishment by drafts from the second, marched, in October, to
Dover Castle; and in January, 1807, returned to Deal. In April
following it embarked for Gibraltar, where it arrived on the 2nd of
June, in a very complete and efficient state, and it passed the
succeeding twelve months at that important fortress.

1808
While the Sixth were in garrison at Gibraltar, the tyrannical
proceedings of Bonaparte in Portugal and Spain, and the resistance
which he met with in those countries, induced the British
Government to aid the patriots in their endeavours to shake off the
French yoke; and in June, 1808, this regiment, mustering upwards
of eleven hundred men, was placed under the orders of Major-
General Brent Spencer, with the view of being employed in this
service. For some time, however, the point at which a landing should
take place was not decided, and the troops appeared first off Ceuta,
then proceeded to Cadiz, subsequently to Lisbon, and back to Cadiz.
At length circumstances occurred which induced Major-General
Spencer once more to proceed to the vicinity of Lisbon, where he
learnt that Lieut.-General Sir Arthur Wellesley had arrived, with eight
thousand men from Ireland, in the Mondego river, and immediately
proceeded thither to join him.
Having landed on the shores of Portugal, the Sixth were formed in
brigade with the thirty-second regiment, under Brigadier-General
Bowes; the advanced guard quitted the banks of the Mondego river,
on the 9th of August, and on the 17th attacked the French under
General Laborde in their position at Roleia.
On the morning of this day, which is memorable for being the first
of a series of victories gained by the British troops in the Peninsula,
the Sixth issued from Obidos, a town with a Moorish castle, built on
a gentle eminence in the middle of a valley, and, directing their
march to the left, gained the ridge of heights on the enemy's right.
They formed part of the left column of attack under Major-General
Ferguson, destined to turn all the enemy's posts on the left of the
valley, and the right of his post at Roleia; also to oppose the efforts
of a body of French troops under General Loison, should they arrive
from Rio Major during the action. The heights were cleared, the
column descended from the higher grounds in the rear of the centre,
and joining Brigadier-General Fane's brigade, were directed through
the mountains to outflank the French right. Meanwhile the troops
which attacked the enemy's centre were triumphant; the Sixth and
other corps in the left column turned his right flank, and he fell back
fighting to the Quinta de Bugaliera, and soon after four o'clock the
action had ceased. The Sixth were not seriously engaged: their only
loss was Captain John Currey and two men wounded, and one man
missing; but their gallant bearing, and eagerness to engage their
adversaries were conspicuous, and they were rewarded with the
honour of bearing the word "Roleia" inscribed on their colours.
On the 19th of August the Sixth marched into position at Vimiera,
a village near the sea-coast, and situate in a valley through which
runs the little river Maceira; and the regiment was one of the corps
posted on a large mountain which commenced at the coast. At
seven o'clock on the morning of the 21st of August a cloud of dust
was observed beyond the nearest hills, and soon afterwards the
French army, commanded by Marshal Junot, was seen advancing in
order of battle.
The Sixth, and several other corps, were directed to cross the
valley behind the village, and to take post on another height, which
overtopped the hill in front of the village; and, before the regiment
reached the summit, the battle had commenced. A sternly contested
action among rugged rocks and broken grounds ended in an entire
defeat of the French army; and the Sixth were rewarded with the
honour of bearing the word "Vimiera" inscribed on their colours.
These successes were followed by the convention of Cintra, and
the British soldiers saw their gallant efforts succeeded by the
deliverance of Portugal from the power of the enemy. On the
departure of the French, the Sixth marched up the country to the
strong fortress of Almeida, situate on the river Coa, in the province
of Beira, where they remained in garrison four months.

1809

In the mean time reports were circulated of the insurrection


against the French, and it was affirmed that enthusiastic multitudes
of Spaniards were pressing forward from every quarter to complete
the destruction of the legions of Napoleon, which were stated to be
baffled, dispirited, and on the eve of quitting Spain. Although the
accounts given by the Spaniards of their own strength and power
were absurdly exaggerated, yet the British government, placing
some confidence in the immense numbers of the patriots, and in the
goodness of their cause, sent Lieut.-General Sir John Moore with an
army into Spain to aid them in their laudable exertions to effect their
emancipation; and the Sixth were withdrawn from Almeida to take
part in this hazardous enterprise. After passing the frontiers of
Portugal and pushing forward boldly into Spain, the British troops
met with disappointment and disaster. Bonaparte had passed the
Pyrenees with a powerful army, and rushing like a tempest upon the
undisciplined multitudes of patriots, he quickly broke, destroyed, and
dispersed them; then bending his course to Madrid, entered the
capital in triumph. Little remained to be done to complete the
conquest of Spain, but the destruction of the army of Britons, who,
by long and toilsome marches through a difficult country, had
ventured to menace his lines, and were the only troops in Spain
capable of resisting his veteran legions. Quitting Madrid, he
advanced with an immense army capable of enveloping and of
swallowing up the handful of British troops; but Sir John Moore, with
his characteristic energy and skill, withdrew towards the coast, and
escaped the toils of his adversary. The Sixth were nearly eight
hundred strong; they were commanded by Major Gordon, and were
brigaded with the ninth, twenty-third, and forty-third regiments,
under Major-General Beresford: they suffered most severely in the
long and harassing retreat over mountains and rivers, through
narrow defiles, and along roads covered with snow; but on arriving
at Corunna, the men obtained shelter in the neighbouring villages
and recruited their wasted strength. While the troops were waiting
the arrival of transports, the French army approached, and, on the
16th of January, 1809, was fought the hard-contested battle of
Corunna, in which British valour and endurance were conspicuously
displayed, and this disastrous expedition was terminated by a
glorious victory, which reflected lustre on the British arms; but the
officers and soldiers had to lament the loss of their gallant leader,
Lieut.-General Sir John Moore, who was mortally wounded during
the heat of the action.
After this victory the troops embarked for England: the Sixth were
one of the last corps which went on board the transports, having
lined the walls of Corunna during the embarkation; and, on arriving
in England, it was ascertained that they had lost about four hundred
men in this arduous enterprise, in which they earned the honorary
distinction of bearing the word "Corunna" inscribed on their colours.
The regiment remained in England until the middle of July, when
the first battalion, having been completed to its establishment by
drafts from the second, embarked with the expedition against
Holland commanded by Lieut.-General the Earl of Chatham. In the
siege and capture of Flushing and the reduction of the island of
Walcheren, the regiment had only Ensign Addison and a few men
wounded; but when the Walcheren fever broke out among the
troops, its ranks were thinned by the ravages of that pestilential
disease. The object of the expedition having been frustrated by
delays, the island was evacuated; and in December the Sixth
returned to England so reduced in numbers, and the sick men so
numerous, as to be unable to furnish the usual reliefs of the ordinary
regimental guard.

1810
1811
1812

In August, 1810, the first battalion embarked at Dover, for Ireland,


and was stationed at Cork and Kinsale until October, 1812, when it
embarked for the Peninsula. Previous to going on board the
transports it was inspected by Lieut.-General Sir John Hope, the
Commander of the Forces in Ireland, who was pleased to express
himself much gratified at witnessing the high state of discipline, and
the general appearance and efficiency of the corps.
The Sixth, commanded by Lieut.-Colonel Archibald Campbell,
arrived at Corunna on the 28th of October; but as the allied army,
commanded by Field-Marshal the Marquis of Wellington, had
evacuated Madrid, and was retiring from Burgos upon Salamanca,
the transports again put to sea, and proceeded to Lisbon, where the
regiment landed on the 15th of November, on which day it was
joined by four hundred men from the second battalion at Jersey.

1813

After halting a short period at the capital of Portugal, the regiment


marched up the country to join the allied army; and taking the field
in May, 1813, had the honour of serving in one of the most brilliant
campaigns on record, in which the legions of Buonaparte were
overthrown in a pitched battle, the barrier of the Pyrenees was
forced, and the victorious British soldiers trod the soil of France in
triumph. The Sixth, with a provisional battalion (formed of the
second battalions of the Twenty-fourth and Fifty-eighth regiments),
and the light infantry of the Brunswick Oels, composed the brigade
of Major-General Edward Barnes, in the seventh division commanded
by Lieut.-General the Earl of Dalhousie.
The Marquis of Wellington appeared at the head of a magnificent
and well-appointed army, and, after passing the frontiers of Portugal,
the tide of war, directed by the comprehensive mind of so able a
commander, flowed onwards with majestic violence: formidable
positions were turned; the rivers Esla, Tormes, Carion, Pisuerga,
Arlanzan, and Ebro, were crossed in succession; and the
obstructions of rocks, mountains, and deep ravines were overcome
with a facility which bespoke the ability of the commander and the
excellent quality of the troops serving under his directions. As the
allied army advanced, the enemy fell back in tumult and disorder,
evacuating strong posts without firing a shot, destroying defensive
works, and calling in detachments with precipitation, until his forces
were concentrated in the valley of Vittoria, where he prepared to
make a resolute stand.
On the morning of the memorable 21st of June, 1813, the Sixth
moved from their camp on the river Bayas, and traversed the
mountains in the direction of Vittoria, to engage in the attack of the
enemy's formidable position; but so rugged was the country, and the
tracts along the hills so difficult, that the battle was raging with great
violence when the division, led by the Earl of Dalhousie, arrived at
their appointed station. They were, however, in time to take part in
forcing the passage of the Zadora; and the seventh division, with
one brigade of the third, having passed the river, formed the left of
the British line, and were engaged with the French right in front of
the villages of Margarita and Hermandad. Finally a complete and
most decisive victory was gained. The conduct of the Earl of
Dalhousie and his division was commended in the public despatch;
the commanding officer of the Sixth, Lieut.-Colonel Archibald
Campbell, was presented with a gold medal, and the gallantry of the
regiment was rewarded with the honour of bearing the word
"Vittoria" inscribed on its colours.
The Sixth moved forward in pursuit of the wreck of the French
army in the direction of Pampeluna; but were subsequently detached
against a division of the enemy under General Clausel, who was not
at the battle, and had taken post at Logroño, from whence he made
a precipitate retreat to Saragossa, and effected his escape by the
pass of Jaca.
After returning from this enterprise the regiment penetrated the
Pyrenean mountains; and the light and seventh divisions occupied
the heights of Santa Barbara, the town of Vera, and the Puerto de
Echalar, and communicated with the troops in the valley of Bastan.
The French army, having been re-organised under Marshal Soult,
attacked the British posts on the 25th of July. The Sixth, with the
remainder of their brigade, moved forward to support two brigades
of the second division which had been forced from their ground at
the head of the valley of Bastan, and the enemy was driven back
with loss. But the brigades in Roncesvalles having been obliged to
retire, the troops in the valley of Bastan also fell back to a very
strong post in the mountains behind Irueta. The regiment lost
several men on this occasion, and had Major Gomm and Ensign
Radcliff wounded. Its conduct, with that of the other corps engaged,
was commended by the Marquis of Wellington, who observed in his
despatch:—"Notwithstanding the enemy's superiority of numbers,
they acquired but little advantage over these brave troops during the
seven hours they were engaged. All the regiments charged with the
bayonet."
From Irueta the Sixth retired with their division to the Lizasso, and
on the 29th of July took post in the mountains near Marcolain, to
connect the operations of the main body of the army with Lieut.-
General Sir Rowland Hill's corps. Some sharp fighting took place in
the mountains on the following day. The Sixth were engaged in
carrying the height which separated the enemy's right flank, and had
Lieutenant Sandys and several men wounded.
When Marshal Soult found himself frustrated in his attempt to
relieve Pampeluna, and retired with the main body of his army,
leaving a strong corps in an excellent position in the pass of Donna
Maria, the Sixth moved forward in pursuit, and, with the remainder
of the seventh division and Sir Rowland Hill's corps, ascended the
two flanks of the mountain on the 31st of July, and dislodged the
enemy in gallant style.
The army continued to press on the rear of the French, and the
fourth and seventh divisions proceeded by the valley of the Bidassoa
towards the frontiers of France. The Sixth, with the remainder of the
Earl of Dalhousie's division, marched on the morning of the 2nd of
August a distance of ten miles over mountains and ridges, along
paths frequented only by shepherds and wild goats, from Sumbilla
towards the Puerto de Echalar, where two French divisions were
found in a formidable position on the height, with nearly the whole
of their army posted behind the Puerto. The division was in advance,
and the enemy appeared in force. But military ardour, with
confidence in the prowess of the officers and men, occasioned the
prudential caution of waiting the arrival of additional troops to be
disregarded, and Major-General Barnes formed his brigade for the
attack. The Sixth composed more than half the brigade: having
received drafts regularly from the second battalion on home service,
they appeared a fine and gallant body of men, all eager to engage
their opponents. The provisional battalion and Brunswickers forming
the remainder of the brigade, though inferior in numbers, were
animated with the same spirit as the Sixth, and the gallant Major-
General Barnes led the three battalions up a ridge which it appeared
almost madness to have attacked. The officers and men, ascending
the heights with cheerful alacrity, confronted, with firm and steady
ranks, their numerous opponents, and advanced to the charge with
that determined resolution for which Britons have been celebrated,
and which occasioned a distinguished officer to say, "Barnes set at
the French as if every man had been a bull-dog, and himself the
best bred of all." It was a moment of trial: the innate bravery of the
officers and men was put to the test; but by a powerful effort, in
which the national character was eminently displayed, they forced
the two divisions of the enemy from these formidable heights, and
were pursuing their victorious career, when orders were received to
halt. The Marquis of Wellington witnessed this brilliant achievement
with feelings of exultation, and expressed his admiration in terms
which occasioned the following order to be issued immediately.

"Heights above Echalar, half-past three o'clock,


2nd August, 1813.
"Division Order.—The Lieutenant-general has just been desired
by Lord Wellington to say to the brigade under Major-General
Barnes' command, that 'Their attack on the enemy is the most
gallant, and the finest thing he ever witnessed.' These were the
words of the Commander of the forces, and Lord Dalhousie feels
the highest satisfaction in communicating them to Major-General
Barnes, the officers, and men."
In his public despatch, the Marquis of Wellington observed:
—"Major-General Barnes's brigade was formed for the attack, and
advanced before the fourth and light divisions could co-operate, with
a regularity and gallantry which I have seldom seen equalled, and
actually drove the two divisions of the enemy, notwithstanding the
resistance opposed to them, from those formidable heights. It is
impossible that I can extol too highly the conduct of Major-General
Barnes and these brave troops, which was the admiration of all who
were witnesses of it."[36]
On this memorable occasion, of which every officer and soldier of
the Sixth may be justly proud, the regiment had Captain William
Brownlow, two serjeants, and thirteen rank and file killed; Major Guy
Campbell, Lieutenants Everest, Tarleton, and Addison, four serjeants,
and one hundred and thirty-six rank and file wounded. Majors Guy
Campbell, Hugh Maurice Scott, and Henry Gomm were promoted to
the rank of lieutenant-colonel, and the regiment was rewarded with
the honour of bearing the word "Pyrenees" inscribed on its colours.
The Sixth were stationed several weeks in the lofty Pyrenean
mountains: the corps at Roncesvalles and Maya stood in a most
commanding situation, and the Marquis of Wellington resolved to
place his left in an equally menacing position, by dispossessing the
enemy of some strong ground on the right of the Bidassoa, the key
of which was a steep mountain, called La Rhune. The attack was
commenced on the 7th of October, and completely succeeded. A
detachment of the Sixth, sent forward through the Puerto de Echalar,
was partially engaged, and had Captain Shawe and one man killed;
Captain Rogers, one serjeant, and five rank and file wounded.
In the attack of the enemy's position on the Nivelle, on the 10th of
November, the Sixth were in the column under Marshal Sir William
Beresford, which carried the redoubts on the left of the enemy's
centre; advanced on the left of the river upon St. Pé; crossed the
stream at that place, and drove a body of French from the heights
beyond the village: in which service the regiment had one man killed
and six wounded; and its gallant bearing was rewarded with the
privilege of displaying the word "Nivelle" on its colours.
In the passage of the Nive, and the actions of the 9th, 10th, 11th,
12th, and 13th of December, the regiment co-operated, but was not
brought into contact with the enemy; and the army afterwards went
into quarters until the severity of the weather was abated.

1814

Operations were, however, recommenced in February, 1814, and


the regiment formed part of the corps under Sir William Beresford,
who attacked, on the 22nd of that month, the fortified posts at
Hastingues and Oyergave, and obliged the enemy to retire within the
tête de pont at Peyrehorade.
The enemy being in position at Orthes, the Sixth, and other corps
under Sir William Beresford, crossed the Gave de Pau on the
morning of the 26th of February, and moved along the high road
from Peyrehorade towards Orthes. On the following day they
advanced to attack the enemy's right, on the heights on the high
road to Dax, and at the village of St. Boes. The village was carried
by the fourth division; and the Sixth advanced in column to turn the
head of a ravine between themselves and the enemy; but on
emerging from the village they were ordered to form line. Colonel
Ross's brigade of horse artillery came up at full speed and
unlimbered in the rear of the regiment, when sections were thrown
back to permit the fire of the artillery to pass through the line. The
ground was, however, so low that the troops could not deploy to
attack the heights. The Sixth moved forward, and in the after
descent of the back of the ravine the French fire told heavily on the
regiment. Several officers and many men fell; Lieut.-Colonel
Gardiner, of the Sixth[37], who commanded the brigade on this
occasion, had his horse killed under him while leading the regiment
forward, and as a serjeant and a private were extricating him from
under the animal, the private was shot through the chest and died
instantly, and the serjeant's hands were both pierced by musket-
balls: one of the colour-staves was also damaged by a ball. At this
moment the Marquis of Wellington came galloping past the
regiment, and cried, "Sixth, incline to your right;" which was obeyed;
but the ground was so rugged, and the enemy's fire so heavy, that
some confusion took place: the road was, however, boldly gained;
and from a ditch and earthen bank the regiment opened a
destructive fire on the enemy, who were in line on each flank, and,
some kneeling and others lying on the ground, kept up a heavy
cross fire. Meanwhile the left of the height on which the enemy's
right stood had been carried; Sir Rowland Hill had also forced the
passage of the Gave above Orthes; and the troops opposed to the
Sixth eventually gave way, when the regiment moved forward in
pursuit.
The regiment lost, on this occasion, Lieutenants Patullo and Scott,
five serjeants, and nineteen rank and file killed; Captains Rogers,
Thompson, Smith, and Fitzgerald, Lieutenants Jones, Craufurd, and
Gilder, with Ensigns St. Clair and Blood, sixteen serjeants, one
drummer, and a hundred and four rank and file wounded. Colonel
Gardiner, who commanded the brigade, and Lieut.-Colonel Scott,
who commanded the regiment, were presented with gold medals;
and the word "Orthes" was inscribed on the regimental colours as a
testimony of its gallantry.
On the 8th of March the regiment was detached, with other forces
under Sir William Beresford, towards Bourdeaux: the French troops
in garrison withdrew to the right of the Garonne, and on the 12th of
that month, as the British approached the town, they were met by
the civil authorities and population of the place, and were received
into the city with acclamations; the magistrates and city-guards
removing the tri-coloured and displaying the white cockade.
The Sixth were subsequently employed against the French troops
on the Garonne and Dordogne; and on the 5th of April two
companies attacked the rear of a column of the enemy and took
many prisoners. The regiment was afterwards employed in investing
the fort of Blaye, which commanded the navigation of the Garonne;
in which service it was engaged when Buonaparte abdicated the
throne of France, and the Bourbon dynasty was restored, which
gave peace to Europe.
The distinguished part which the Sixth had taken in the splendid
achievements by which the kingdoms of Portugal, Spain, and France
had been delivered from the despotic rule of Buonaparte was
rewarded with the honour of bearing the word "Peninsula" on their
colours. Soon after the termination of the contest in Europe they
were destined to transfer their services across the Atlantic, to take
part in the war between Britain and the United States of America,
which commenced in 1812, in consequence of the resistance of the
Americans to the British orders in council respecting the trade of
neutral nations, and to the impressing of British seamen on board of
American ships. The regiment embarked from Bourdeaux on the 5th
of May, arrived in Canada in the beginning of July, and proceeded to
Montreal, from whence it was removed to the Niagara frontier to
reinforce the division commanded by Lieut.-General Gordon
Drummond, who was engaged in the siege of Fort Erie. Having
joined this division of the army, the Sixth formed part of the reserve
brigade; and on the 6th of September the eighth company,
commanded by Captain Pattison, cut off a strong piquet of
Americans close under the walls of the fort, in a manner very
creditable to the discipline, spirit, and enterprise of the officers and
men. On the 17th of the same month the regiment was engaged in
repelling a very bold sortie made by a numerous body of Americans,
with the view of carrying by assault, and afterwards destroying, the
British works and batteries; on which occasion the following order
was issued:—

"Camp before Fort Erie,


18th September, 1814.
"District General Order.—Lieut.-General Drummond, having
received the report of the general officer in the immediate
direction of the troops engaged yesterday, begs to offer his best
acknowledgments for their very gallant conduct in repulsing the
attack made by the enemy on our batteries with his whole force,
represented as consisting of not less than five thousand men,
including the militia.
"The brilliant style in which the battery No. 2 was recovered,
and the enemy driven beyond our entrenchments by seven
companies of the Eighty-second, under the command of Major
Proctor, and three companies of the Sixth regiment, detached
under Major Taylor, excited Lieut.-General Drummond's
admiration, and entitle those troops to his particular thanks."
Thus the Sixth were triumphant in the interior of France and on
the frontiers of Canada in the same year, and their gallantry on the
last occasion procured for them the royal permission to bear the
word "Niagara" inscribed on their colours. This honour was, however,
purchased with the loss of many lives: Captain Pattison was
numbered among the slain; Captain Smith and Lieutenant Andrews
were wounded, and the last-mentioned officer died of his wounds.
A treaty of peace having been concluded with the Americans,
hostilities ceased, and the Sixth reposed a short period in quarters.

1815

In the summer of 1815, the return of Buonaparte to France having


rekindled the flame of war in Europe, the Sixth were directed to
embark from America, in order to engage once more in actual
warfare. They left Canada in the beginning of July, landed at Ostend
on the 10th of August, and proceeded to Ghent, from whence they
continued their march to Paris, and joined the army commanded by
Field-Marshal His Grace the Duke of Wellington, encamped near that
city. The Sixth, sixteenth, fifty-eighth, and eighty-second regiments
formed the fifteenth brigade, and were posted in the seventh
division, commanded by Major-General Thomas Brisbane.
When the definitive treaties between France and the allied powers
were settled, the Sixth were selected to form part of the army of
occupation in France, and constituted, with the twenty-ninth and
seventy-first regiments, the sixth brigade of infantry, under Major-
General Sir Thomas Bradford, in the second division, commanded by
Lieut.-General Sir Henry Clinton. The Sixth were quartered at
Versailles, from whence they marched, in December, to Ecouen, a
village on the road from Paris to Luzarches.
On the 24th of December, 1815, the second battalion was
disbanded at Winchester.

1816
The Sixth remained in the neighbourhood of Ecouen until the 23rd
of January, 1816, when they marched for St. Pol in the Pas de Calais,
and in February three companies occupied Lillers, and seven the
adjacent villages.
In August, 1816, the regiment proceeded to the vicinity of St.
Omer, and encamped, with the remainder of the second division of
the British contingent of the army of occupation, on Helfant Heath.
In October it proceeded to the plains of Denain, near Valenciennes,
where the British contingent was reviewed by Field-Marshal His
Grace the Duke of Wellington on the 22nd of that month. After the
review the regiment returned to its former cantonments at Lillers
and the neighbouring villages.

1817
1818

The Sixth were again encamped on Helfant Heath in July, 1817; in


September they pitched their tents on the glacis of Valenciennes,
near the Quesnoy gate; and on the 6th of that month were
reviewed, with the remainder of the British infantry, by the King of
Prussia. They removed in October to the plains of Denain, where the
British contingent was reviewed by the Duke of Wellington on the
15th of October; on the 20th the Sixth returned to their former
quarters at Lillers, &c. In these quarters they remained until June,
1818, when they once more pitched their tents on Helfant Heath,
where they were reviewed by Lieut.-General Lord Hill on the 24th of
June, and by the Duke of Wellington on the 31st of July. In August
they again pitched their tents on the glacis at Valenciennes. On the
10th of September the British, Saxon, Danish, and Hanoverian
armies, commanded by the Duke of Wellington, were reviewed by
His Royal Highness the Duke of Kent; and on the 23rd of October,
the same troops, and also the Russian contingent, were reviewed by
the Emperor of Russia, King of Prussia, &c. After the review, the
army of occupation was withdrawn from France. The Sixth embarked
at Calais on the 29th of October, landed on the morning of the 30th
at Dover, and marched to Romford in Essex, where the
establishment was reduced to ten companies, of thirty-nine officers,
thirty-five serjeants, thirty corporals, twenty-two drummers, and six
hundred and twenty private men.

1819
1820

From Romford the Sixth marched in November to Sunderland and


Carlisle, and in June, 1819, to Edinburgh Castle, with one company
detached to Stirling, another to Aberdeen, and in the autumn a
company was detached to Berwick. In consequence of the disturbed
state of the northern counties of England, seven companies were
ordered into Yorkshire—four companies proceeding to Leeds, and
three to Halifax: the company left at Berwick arrived at Halifax, and
the two companies left at Edinburgh at Leeds, in January, 1820. At
an inspection on the 27th of April following, Lieut.-General Sir John
Byng expressed his approbation of the appearance, discipline, and
interior economy of the regiment; and also at the inspection on the
22nd of May, 1821.

1821

The Sixth remained at Leeds and Halifax until June, 1821, when
they proceeded to Hull, and embarked for the island of St. Helena.
Two companies had sailed for their destination when information
arrived of the death of Napoleon Buonaparte in exile at St. Helena.
The remainder of the regiment then proceeded to the Downs, where
its destination was changed to the Cape of Good Hope, and after a
tedious voyage arrived on the 3rd of November at Table Bay, where
it was joined by the two companies from St. Helena. Having landed,
the regiment was inspected by Lieut.-General Sir Rufane Donkin,
K.C.B., at Cape Town, and was commended for its appearance,
conduct, and efficient state—its effectives being only one man less
than on its embarkation from England. After remaining a few days
on shore, five companies, under Brevet-Major Rogers, re-embarked
and sailed to Algoa Bay, from whence they proceeded to Graham's
Town, and marched from thence to several posts and forts along the
frontier line. The establishment had, in the mean time, been reduced
to eight companies of thirty-three officers and six hundred and
eighteen non-commissioned officers and private soldiers.

1822

In January, 1822, the head-quarters, under Brevet Lieut.-Colonel


Scott, embarked from Cape Town, and arrived at Graham's Town
towards the end of the same month; at the same time Lieut.-Colonel
Scott took the command of the troops on the frontier line of
Caffreland. The regiment was stationed along the frontiers, and was
much employed in patrolling and other duties to prevent the
aggressions of the natives. When not thus occupied, the men were
engaged as labourers and artificers at the government works.

1823

In October, 1823, the flank companies proceeded to Cape Town,


and were followed by the head-quarters in November. Colonel Mark
Napier, having arrived at the Cape, assumed the command of the
regiment; Lieut.-Colonel Scott was nominated commandant at
Simonstown, and the command of the six companies left on the
frontiers of Caffreland devolved on Captain Cox.

1824
1825

In August and September, 1824, four companies were withdrawn


from the frontiers and joined the head-quarters: in January, 1825,
the regiment was inspected at Cape Town by Lieut.-General Lord
Charles Henry Somerset, who was pleased to express himself much
gratified at witnessing its good appearance after being so long
detached, and the men employed in working parties.
The regiment had in the mean time been placed on the India
establishment; and the usual augmentation of officers arrived at the
Cape of Good Hope in March, 1825. On the 22nd of March it
embarked at Table Bay on board the Windsor and Vansittart,
Indiamen, and landed on the 31st of May at Bombay. It occupied the
barracks at Fort George, and, Colonel Napier having been appointed
commandant of the fort and garrison, it was commanded by Lieut.-
Colonel Scott. It was inspected on the 9th of June by Major-General
Samuel Wilson, of the Hon. East India Company's service, who
expressed himself much pleased with the steady and veteran
appearance of the men, and particularly commended its interior
economy.
In June, 1825, the establishment was augmented to a thousand
and eight rank and file. During that and the following months the
regiment suffered severely from the cholera morbus, which carried
off many of the finest and strongest men: the mortality was
particularly great among the women and children.
At the close of the rainy season, in September, the regiment was
suddenly ordered from Bombay to form part of a field-force
assembling at Cutch, with a view to the invasion of Scinde, between
the umeers of which country and the Bombay government serious
differences had arisen, in consequence of the incursions of a tribe of
Mayanas on the Cutch frontier. The regiment embarked from
Bombay on the 21st of September, four hundred and sixty-eight
strong, landed at Mandavie, in the gulf of Cutch, between the 10th
and 15th of October, and marched towards Bhooj, the capital,
beyond which city it pitched its tents, on the 2nd of November, near
the village of Juruck, where eight thousand men were assembled
under the command of Colonel Mark Napier of the Sixth. It was
formed in brigade with the Twenty-first regiment of Sipahees and
the flank companies of the second Bombay European regiment,
under the orders of Lieut.-Colonel Scott of the Sixth; and the
command of the regiment devolved on Major Algeo.
On the 3rd of December the troops moved from Juruck to the
neighbourhood of Raddiapoor, and, Colonel Napier being obliged to
leave the army from indisposition, the command devolved on Lieut.-
Colonel Scott of the Sixth. While at this camp six officers and
seventy-seven fine recruits, from Yorkshire and Lancashire, joined
the regiment.

1826

In January, 1826, the army removed to Madapoor; in February it


encamped near the fort and city of Bhooj; and, in March, the umeers
of Scinde having yielded to the demands of the Bombay
government, the regiments were ordered back to their different
stations. The Sixth embarked from Mandavie on the 20th and 21st of
March, in pattimars (small craft with open decks); arrived at the
presidency on the 26th and 30th of that month, and occupied the
barracks on the little island of Colaba. Its loss from sickness, during
the first six months after its arrival in India, was one officer and
sixty-nine men, and forty-one invalided.
Brevet-Major Thompson, Lieutenant Gordon, and one hundred and
forty-six recruits, joined from England in the beginning of May; and,
at the inspection on the 18th of that month, Major-General Wilson
commended the appearance and orderly conduct of the regiment in
quarters, which he repeated at the inspection on the 14th of
December. During the year 1826 the regiment lost four officers and
fifty men.

1827

Lieut.-Colonel Scott, commandant of the fort and garrison of


Bombay, inspected the regiment on the 3rd of May, 1827, and
expressed his satisfaction at its appearance and condition. On the
8th of that month six officers and one hundred and eighty men
joined from England. The decease of Lieut.-Colonel Scott occurred in
October following, and Major Algeo of the Sixth assumed the
command of the fort and garrison of Bombay, until the arrival of
Colonel Henry Sullivan in November, when Major Algeo resumed the
command of the regiment. Colonel Sullivan inspected the regiment
on the 15th of December, and every department met with his
approval. During the year 1827 the regiment lost two officers and
forty men; and invalided twenty-three men.

1828

Seven officers and two hundred and eleven men joined from
England in May, 1828. During the heavy rains many men were
carried off by the cholera morbus; in the month of July alone the
Sixth lost fifty-eight men from this disease. This was a year of
general sickness all over India; but at no station did any regiment
suffer so much as the Sixth on Colaba island; their loss being two
officers and one hundred and twenty one men, and they sent sixty-
two invalids to England.

1829

The very sickly state of the regiment, from its having been
stationed during four monsoons at Bombay, occasioned it to be
removed to the more healthy station of Poona in the Deccan: it
embarked from Colaba on the 6th of February, 1829, landed at
Panwell on the opposite coast in the evening, and marched for
Poona, where it arrived on the 17th, and was stationed in the lines
then recently occupied by the twentieth regiment. The health of the
men began to improve rapidly, and in a few months the Sixth were
one of the most healthy and efficient corps in India. In May one
hundred and thirty-five volunteers from the forty-seventh regiment
joined the Sixth in camp at Poona; and at the inspection, on the 10th
of June, Major-General Sir Lionel Smith, K.C.B., expressed himself
much gratified with the appearance and efficiency of the corps. The
loss from disease during this year was thirty-two men.

1830

The condition of the regiment was also much commended by Sir


Lionel Smith at the inspections in January and June, 1830. In July
the flank companies were ordered to be completed to one hundred
rank and file each, under the command of Captain Murphy, with the
second or Queen's royal, and flank companies of the eleventh and
thirteenth native infantry, the whole to be commanded by Colonel
Willshire, to march against Ukkulcote; but this fort having
surrendered to the troops under the President of Sattara (Lieut.-
Colonel A. Robertson, the Resident at the court), the march was
countermanded. In December the strength of the regiment was
increased by the arrival at the camp at Poona of fourteen volunteers
from the first, or the royals, and ninety-two from the eighty-ninth
regiment. Its loss from disease this year was three officers and
twenty-four men.

1831

At the inspections in January and June, 1831, Colonel Henry


Sullivan, commanding the Poona division, expressed his unqualified
approbation of the condition of the regiment. This year it was
particularly healthy, its loss being only one officer and eight men;
and when inspected in November, by Major-General Sir James
Stevenson Barns, K.C.B., commanding the forces in the Bombay
presidency, its appearance, discipline, efficiency, and general good
conduct in quarters, were commended.

1832

The regiment remained at Poona during the year 1832, and on the
24th of May, 1832, His Majesty King William IV. was graciously
pleased to confer upon it the title of Sixth, or Royal First Warwickshire
Regiment of Foot[38]; at which time its facings were changed from
yellow to blue.

1833
1834
1835
1836
1837
1838
In January, 1833, the regiment was at Panwell, in February it was
encamped near Dungah, and in March at Deesa, where it remained
during that and the two succeeding years, when it proceeded to
Colaba. It was stationed at Colaba during the years 1836 and
1837[39]; and in the beginning of 1838 returned to cantonments at
Poona, where it has remained until the end of the year; which brings
this record to a conclusion.
The formation of the Sixth, or Royal First Warwickshire Regiment, in
1674, to support the cause of civil and religious liberty in Holland
against the power of the ambitious Louis XIV. of France, gives an
interesting character to its origin, and also to its early services in
support of the Protestant interests. At the Revolution, in 1688, it had
the honour to compose part of the army which appeared in England
to rescue the country from the dangers by which it was menaced. It
aided in delivering Ireland from the power of papacy, and afterwards
fought under King William III. in the Netherlands. In the war of the
Spanish succession it performed much sharp fighting and arduous
duty in Spain. Its services at home, and in the West Indies, have
been of an important character. It had the honour to gain laurels
under Lieut.-General Sir John Moore, and also under the Duke of
Wellington, in Portugal, Spain, and France, and acquired distinction
on the distant shores of Lake Erie in North America. During the last
eighteen years it has been employed in protecting the British colonial
possessions in Africa and Asia, a service from which important
commercial advantages are derived by the country.
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

ebooknice.com

You might also like