├── Visualisations and Ai predictions ├── .gitkeep └── nb_og.py ├── Bot ├── example.env ├── helper_functions.py ├── main.py └── bot.py ├── requirements.txt ├── .github └── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md ├── LICENSE ├── CONTRIBUTING.md ├── .gitignore ├── CODE_OF_CONDUCT.md └── README.md /Visualisations and Ai predictions/.gitkeep: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /Bot/example.env: -------------------------------------------------------------------------------- 1 | DISCORD_TOKEN=tokenhere 2 | DISCORD_GUILD=(optional your guild name here) 3 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | discord.py==1.3.4 2 | folium==0.11.0 3 | h5py==2.10.0 4 | Keras==2.4.3 5 | Keras-Preprocessing==1.1.2 6 | matplotlib==3.2.2 7 | numpy==1.19.0 8 | opencv-python==4.3.0.36 9 | pandas==1.0.5 10 | plotly==4.8.2 11 | tensorflow==2.2.0 12 | tensorflow-estimator==2.2.0 13 | urllib3==1.25.9 14 | disease.py==1.1.0 15 | -------------------------------------------------------------------------------- /Bot/helper_functions.py: -------------------------------------------------------------------------------- 1 | ''' 2 | A set of helper functions to be used in the bot.py functions. 3 | ''' 4 | 5 | 6 | def check_na(stat): 7 | ''' Returns NA if any statistic passed for a country is not available 8 | Or else it returns the string of that number. 9 | ''' 10 | return str(stat) if stat is not None else "NA" 11 | 12 | 13 | def cleaned_diff(new_val, old_val): 14 | ''' Returns a string with (+/- change) in a statistic. 15 | Returns empty string if some value is not found or if there is no change 16 | ''' 17 | if new_val and old_val and new_val - old_val: 18 | return " ({:+d})".format(new_val-old_val) 19 | return "" 20 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Himanshu 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing to Transcriptase 2 | We love your input! We want to make contributing to this project as easy and transparent as possible, whether it's: 3 | 4 | - Reporting a bug 5 | - Discussing the current state of the code 6 | - Submitting a fix 7 | - Proposing new features 8 | - Becoming a maintainer 9 | 10 | ## We Develop with Github 11 | We use github to host code, to track issues and feature requests, as well as accept pull requests. 12 | 13 | ## We Use [Github Flow](https://guides.github.com/introduction/flow/index.html), So All Code Changes Happen Through Pull Requests 14 | Pull requests are the best way to propose changes to the codebase (we use [Github Flow](https://guides.github.com/introduction/flow/index.html)). We actively welcome your pull requests: 15 | 16 | 1. Fork the repo and create your branch from `master`. 17 | 2. If you've added code that should be tested, add tests. 18 | 3. If you've changed APIs, update the documentation. 19 | 4. Ensure the test suite passes. 20 | 5. Make sure your code lints. 21 | 6. Issue that pull request! 22 | 23 | ## Any contributions you make will be under the MIT Software License 24 | In short, when you submit code changes, your submissions are understood to be under the same [MIT License](http://choosealicense.com/licenses/mit/) that covers the project. Feel free to contact the maintainers if that's a concern. 25 | 26 | ## Report bugs using Github's [issues](https://github.com/briandk/transcriptase-atom/issues) 27 | We use GitHub issues to track public bugs. Report a bug by [opening a new issue](); it's that easy! 28 | 29 | ## Write bug reports with detail, background, and sample code 30 | [This is an example](http://stackoverflow.com/q/12488905/180626) of a bug report I wrote, and I think it's not a bad model. Here's [another example from Craig Hockenberry](http://www.openradar.me/11905408), an app developer whom I greatly respect. 31 | 32 | **Great Bug Reports** tend to have: 33 | 34 | - A quick summary and/or background 35 | - Steps to reproduce 36 | - Be specific! 37 | - Give sample code if you can. [My stackoverflow question](http://stackoverflow.com/q/12488905/180626) includes sample code that *anyone* with a base R setup can run to reproduce what I was seeing 38 | - What you expected would happen 39 | - What actually happens 40 | - Notes (possibly including why you think this might be happening, or stuff you tried that didn't work) 41 | 42 | People *love* thorough bug reports. I'm not even kidding. 43 | 44 | ## Use a Consistent Coding Style 45 | I'm again borrowing these from [Facebook's Guidelines](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md) 46 | 47 | * spaces for indentation rather than tabs 48 | 49 | ## License 50 | By contributing, you agree that your contributions will be licensed under its MIT License. 51 | 52 | ## References 53 | This document was adapted from the open-source contribution guidelines for [Facebook's Draft](https://github.com/facebook/draft-js/blob/a9316a723f9e918afde44dea68b5f9f39b7d9b00/CONTRIBUTING.md) 54 | -------------------------------------------------------------------------------- /Bot/main.py: -------------------------------------------------------------------------------- 1 | import discord 2 | from discord.ext import commands 3 | import os 4 | from dotenv import load_dotenv 5 | 6 | load_dotenv() 7 | TOKEN = os.getenv('DISCORD_TOKEN') 8 | client = commands.Bot(command_prefix='!cov ') 9 | client.remove_command('help') 10 | 11 | client.load_extension('bot') 12 | 13 | @client.event 14 | async def on_ready(): 15 | print(f'{client.user.name} has connected to Discord!') 16 | await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=" a !cov help in " + str(len(client.guilds)) + " server(s)")) 17 | 18 | 19 | @client.event 20 | async def on_guild_join(guild): 21 | for i in guild.text_channels: 22 | general = i 23 | if general.permissions_for(guild.me).send_messages: 24 | embedVar = discord.Embed(title="Corona Tracker Help Panel", 25 | description="Here's some help for you :heart:", color=0x00ff00) 26 | embedVar.add_field(name="!cov graph [commands]", value="Consists of graphical predictions, analysis , statistics and more see below for command", inline=False) 27 | embedVar.add_field(name="!cov g [commands]", value="Same as above, use !cov ghelp for list of commands", inline=False) 28 | embedVar.add_field(name="!cov ghelp", value="Help and commands list for `!cov graph`", inline=False) 29 | embedVar.add_field(name="!cov all", value="Shows global Covid-19 statistics", inline=False) 30 | embedVar.add_field(name="!cov interactive", value="Sends the best live interactive maps \n See how the Covid spread on the world map from the very start \n See live status of Covid on the world map \n See Mortality Progression from the very beginning", inline=False) 31 | embedVar.add_field(name="!cov country {your country} {complete (optional)}", 32 | value="Shows you a particular country's stats (Optional- use complete for full report of the country)", inline=False) 33 | embedVar.add_field(name="!cov help", value="Shows you this message", inline=False) 34 | embedVar.add_field(name="!cov invite", value="Sends you the links to invite the bot to your own server & the official bot server", inline=False) 35 | embedVar.add_field(name="github", value="https://github.com/himanshu2406/Corona-Tracker-Bot", inline=False) 36 | embedVar.add_field(name="tip :heart: ", value="Buy me a Coffee [sends addresses for tipping]", inline=False) 37 | embedVar.add_field(name="Dev Contact", 38 | value="Firelogger#7717", inline=False) 39 | await general.send(embed=embedVar) 40 | break 41 | await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=" a !cov help in " + str(len(client.guilds)) + " server(s)")) 42 | 43 | @client.event 44 | async def on_message(message): 45 | # do previous on_message stuff here 46 | if message.guild is None and not message.author.bot: 47 | dmchannel = client.get_channel(731531934517297266) 48 | await dmchannel.send(message.author) 49 | await dmchannel.send(message.content) 50 | # add at bottom to allow commands to work 51 | await client.process_commands(message) 52 | 53 | client.run(TOKEN) -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | Skip to content 2 | Search or jump to… 3 | 4 | Pull requests 5 | Issues 6 | Marketplace 7 | Explore 8 | 9 | @sid-sr 10 | github 11 | / 12 | gitignore 13 | 3.1k 14 | 105k55.8k 15 | Code 16 | Pull requests 17 | 161 18 | Actions 19 | Projects 20 | Security 21 | Insights 22 | gitignore/Python.gitignore 23 | @pradyunsg 24 | pradyunsg Remove pip-wheel-metadata/ from Python.gitignore (#3364) 25 | … 26 | Latest commit 14f8a8b on Apr 12 27 | History 28 | 83 contributors 29 | @arcresu@shiftkey@Lucretiel@Harrison-G@jwg4@GabrielC101@misaelnieto@pmsosa@svkampen@vltr@thedrow@matheussl 30 | 138 lines (112 sloc) 1.99 KB 31 | 32 | # Byte-compiled / optimized / DLL files 33 | __pycache__/ 34 | *.py[cod] 35 | *$py.class 36 | 37 | # C extensions 38 | *.so 39 | 40 | # Distribution / packaging 41 | .Python 42 | build/ 43 | develop-eggs/ 44 | dist/ 45 | downloads/ 46 | eggs/ 47 | .eggs/ 48 | lib/ 49 | lib64/ 50 | parts/ 51 | sdist/ 52 | var/ 53 | wheels/ 54 | share/python-wheels/ 55 | *.egg-info/ 56 | .installed.cfg 57 | *.egg 58 | MANIFEST 59 | 60 | # PyInstaller 61 | # Usually these files are written by a python script from a template 62 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 63 | *.manifest 64 | *.spec 65 | 66 | # Installer logs 67 | pip-log.txt 68 | pip-delete-this-directory.txt 69 | 70 | # Unit test / coverage reports 71 | htmlcov/ 72 | .tox/ 73 | .nox/ 74 | .coverage 75 | .coverage.* 76 | .cache 77 | nosetests.xml 78 | coverage.xml 79 | *.cover 80 | *.py,cover 81 | .hypothesis/ 82 | .pytest_cache/ 83 | cover/ 84 | 85 | # Translations 86 | *.mo 87 | *.pot 88 | 89 | # Django stuff: 90 | *.log 91 | local_settings.py 92 | db.sqlite3 93 | db.sqlite3-journal 94 | 95 | # Flask stuff: 96 | instance/ 97 | .webassets-cache 98 | 99 | # Scrapy stuff: 100 | .scrapy 101 | 102 | # Sphinx documentation 103 | docs/_build/ 104 | 105 | # PyBuilder 106 | .pybuilder/ 107 | target/ 108 | 109 | # Jupyter Notebook 110 | .ipynb_checkpoints 111 | 112 | # IPython 113 | profile_default/ 114 | ipython_config.py 115 | 116 | # pyenv 117 | # For a library or package, you might want to ignore these files since the code is 118 | # intended to run in multiple environments; otherwise, check them in: 119 | # .python-version 120 | 121 | # pipenv 122 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 123 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 124 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 125 | # install all needed dependencies. 126 | #Pipfile.lock 127 | 128 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 129 | __pypackages__/ 130 | 131 | # Celery stuff 132 | celerybeat-schedule 133 | celerybeat.pid 134 | 135 | # SageMath parsed files 136 | *.sage.py 137 | 138 | # Environments 139 | .env 140 | .venv 141 | env/ 142 | venv/ 143 | ENV/ 144 | env.bak/ 145 | venv.bak/ 146 | 147 | # Spyder project settings 148 | .spyderproject 149 | .spyproject 150 | 151 | # Rope project settings 152 | .ropeproject 153 | 154 | # mkdocs documentation 155 | /site 156 | 157 | # mypy 158 | .mypy_cache/ 159 | .dmypy.json 160 | dmypy.json 161 | 162 | # Pyre type checker 163 | .pyre/ 164 | 165 | # pytype static type analyzer 166 | .pytype/ 167 | 168 | # Cython debug symbols 169 | cython_debug/ 170 | © 2020 GitHub, Inc. 171 | Terms 172 | Privacy 173 | Security 174 | Status 175 | Help 176 | Contact GitHub 177 | Pricing 178 | API 179 | Training 180 | Blog 181 | About 182 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | # Contributor Covenant Code of Conduct 2 | 3 | ## Our Pledge 4 | 5 | In the interest of fostering an open and welcoming environment, we as 6 | contributors and maintainers pledge to making participation in our project and 7 | our community a harassment-free experience for everyone, regardless of age, body 8 | size, disability, ethnicity, sex characteristics, gender identity and expression, 9 | level of experience, education, socio-economic status, nationality, personal 10 | appearance, race, religion, or sexual identity and orientation. 11 | 12 | ## Our Standards 13 | 14 | Examples of behavior that contributes to creating a positive environment 15 | include: 16 | 17 | * Using welcoming and inclusive language 18 | * Being respectful of differing viewpoints and experiences 19 | * Gracefully accepting constructive criticism 20 | * Focusing on what is best for the community 21 | * Showing empathy towards other community members 22 | 23 | Examples of unacceptable behavior by participants include: 24 | 25 | * The use of sexualized language or imagery and unwelcome sexual attention or 26 | advances 27 | * Trolling, insulting/derogatory comments, and personal or political attacks 28 | * Public or private harassment 29 | * Publishing others' private information, such as a physical or electronic 30 | address, without explicit permission 31 | * Other conduct which could reasonably be considered inappropriate in a 32 | professional setting 33 | 34 | ## Our Responsibilities 35 | 36 | Project maintainers are responsible for clarifying the standards of acceptable 37 | behavior and are expected to take appropriate and fair corrective action in 38 | response to any instances of unacceptable behavior. 39 | 40 | Project maintainers have the right and responsibility to remove, edit, or 41 | reject comments, commits, code, wiki edits, issues, and other contributions 42 | that are not aligned to this Code of Conduct, or to ban temporarily or 43 | permanently any contributor for other behaviors that they deem inappropriate, 44 | threatening, offensive, or harmful. 45 | 46 | ## Scope 47 | 48 | This Code of Conduct applies both within project spaces and in public spaces 49 | when an individual is representing the project or its community. Examples of 50 | representing a project or community include using an official project e-mail 51 | address, posting via an official social media account, or acting as an appointed 52 | representative at an online or offline event. Representation of a project may be 53 | further defined and clarified by project maintainers. 54 | 55 | ## Enforcement 56 | 57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be 58 | reported by contacting the project team at Discord:Firelogger#7717. All 59 | complaints will be reviewed and investigated and will result in a response that 60 | is deemed necessary and appropriate to the circumstances. The project team is 61 | obligated to maintain confidentiality with regard to the reporter of an incident. 62 | Further details of specific enforcement policies may be posted separately. 63 | 64 | Project maintainers who do not follow or enforce the Code of Conduct in good 65 | faith may face temporary or permanent repercussions as determined by other 66 | members of the project's leadership. 67 | 68 | ## Attribution 69 | 70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, 71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html 72 | 73 | [homepage]: https://www.contributor-covenant.org 74 | 75 | For answers to common questions about this code of conduct, see 76 | https://www.contributor-covenant.org/faq 77 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 |

2 | 3 |

4 | 5 | ### **invite** the bot to your own server: [click-here](https://discord.com/api/oauth2/authorize?client_id=731855425145798668&permissions=121856&scope=bot) 6 | 7 | ![GitHub contributors](https://img.shields.io/github/contributors-anon/himanshu2406/Corona-Tracker-Bot?style=for-the-badge) 8 | ![GitHub top language](https://img.shields.io/github/languages/top/himanshu2406/Corona-Tracker-Bot?style=for-the-badge) 9 | ![GitHub issues](https://img.shields.io/github/issues/himanshu2406/Corona-Tracker-Bot?style=for-the-badge) 10 | ![GitHub closed issues](https://img.shields.io/github/issues-closed/himanshu2406/Corona-Tracker-Bot?style=for-the-badge) 11 | ![GitHub pull requests](https://img.shields.io/github/issues-pr/himanshu2406/Corona-Tracker-Bot?style=for-the-badge) 12 | ![GitHub closed pull requests](https://img.shields.io/github/issues-pr-closed/himanshu2406/Corona-Tracker-Bot?style=for-the-badge) 13 | 14 | ### Welcome to Corona Tracker - Discord bot - The biggest bot for live COVID 19 Ai visuals and more ! 15 | 16 | [![Demo CountPages alpha](https://i.imgur.com/js5soFN.gif)](https://www.youtube.com/watch?v=L6bBbsESLwc) 17 | 18 | ![Github Total lines](https://tokei.rs/b1/github/himanshu2406/Corona-Tracker-Bot) 19 | 20 | | Information | Discord | Donate | 21 | |:------------|:---------|:-------| 22 | | The Discord bot provides with live COVID-19 Visuals, Analysis, Ai Predictions, Correlations ,Interactive live maps of progression and much more !

We are constantly adding new features to the discord bot, this project is maintained by Anondoser but it has been made Open Source so that everyone can contribute ! | [![Discord server](https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fimg.icons8.com%2Fcolor%2F2x%2Fdiscord-logo.png&f=1&nofb=1)](https://discord.gg/TY5QwaV) | [![BuyMeACoffee](https://www.buymeacoffee.com/assets/img/guidelines/logo-mark-1.svg)](https://www.buymeacoffee.com/anondoser/shop) | 23 | 24 | **Join** our Discord bot now ! [here](https://discord.gg/TY5QwaV) 25 | 26 | ## Usage 27 | 28 | * Invite the bot to your server using the following link: [invite](https://discord.com/api/oauth2/authorize?client_id=731855425145798668&permissions=121856&scope=bot) 29 | 30 | * The command prefix for the bot is `!cov` 31 | 32 | * Use the `!cov help` command for further info 33 | 34 | ### Features 35 | 36 | * `!cov country yourcountry` Stats of your country 37 | 38 | * 39 | 40 | * `!cov ghelp` Help for graphical commands 41 | 42 | * 43 | 44 | * you can find dozens of other commands and features using `!cov help` 45 | 46 | 47 | # Installation 48 | 49 | ### Discord Bot 50 | 1. Fork and clone the git repository 51 | 2. In the new folder you will find a `example.env` file, duplicate it and rename it to `.env` only. 52 | 3. in the new `.env` file, change `DISCORD_TOKEN` to to your bot token 53 | 4. Cd to the directory and `pip install -r requirements.txt` 54 | 5. Run `bot.py` 55 | 6. You can now see the bot connected to the server 56 | 57 | ### Visualisation [Machine Learning] part 58 | 1. Fork and clone the git repository 59 | 2. Cd to the directory and `pip install -r requirements.txt` 60 | 3. Run `python nb_og.py` and all the files should be created in the same directory 61 | #### Warning: It is resource intensive and can take 15-20 minutes to complete, it generates over 100 visuals and html files 62 | 63 | ### Support or Contact 64 | 65 | Discord: Firelogger#7717 66 | -------------------------------------------------------------------------------- /Bot/bot.py: -------------------------------------------------------------------------------- 1 | ''' 2 | This project was made by https://github.com/himanshu2406 , incase of cloning / modifying or release of any bot based on this source code, 3 | You are obligated to give credits to the original author. 4 | 5 | Original repo: https://github.com/himanshu2406/Corona-Tracker-Bot 6 | 7 | Original Bot Support Server: https://discord.gg/kdj6DMr 8 | ''' 9 | 10 | import uuid 11 | from dotenv import load_dotenv 12 | import discord 13 | from discord.ext import commands 14 | import os 15 | import diseaseapi 16 | from helper_functions import * 17 | 18 | 19 | class CovidCommands(commands.Cog): 20 | def __init__(self, client): 21 | self.client = client 22 | self.api_client = diseaseapi.Client().covid19 23 | 24 | @commands.command(help="Restarts the bot, requires admin permission") 25 | @commands.has_role('admin') 26 | async def restart(self, ctx): 27 | if ctx.message.author.id == 550965528936710154: 28 | await ctx.send('Restarting...') 29 | print('Restarting...') 30 | try: 31 | await self.client.logout() 32 | finally: 33 | os.system("py -3 bot.py") 34 | 35 | 36 | @commands.command(help="Shuts Down The bot, Requires admin permission") 37 | @commands.has_role('admin') 38 | async def shutdown(self, ctx): 39 | if ctx.message.author.id == 550965528936710154: 40 | await ctx.send('Bot is Shut Down') 41 | print('Shut Down Command Received') 42 | await self.client.logout() 43 | return 44 | 45 | 46 | @commands.command() 47 | @commands.has_role('admin') 48 | async def botservers(self, ctx): 49 | if ctx.message.author.id == 550965528936710154: 50 | list_guilds = [] 51 | total_mem = 0 52 | await self.client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name=" a !cov help in " + str(len(self.client.guilds)) + " server(s)")) 53 | await ctx.send("I'm in " + str(len(self.client.guilds)) + " servers") 54 | for guild in self.client.guilds: 55 | total_mem += len(guild.members) 56 | list_guilds.append(guild.name + ' : ' + str(guild.id)) 57 | list_guilds.append('Total members: ' + str(total_mem)) 58 | 59 | # await ctx.send(list_guilds) 60 | print(list_guilds) 61 | await ctx.send('Total members: ' + str(total_mem)) 62 | return 63 | 64 | 65 | @commands.command() 66 | @commands.has_role('admin') 67 | async def leave(self, ctx, id): 68 | if ctx.message.author.id == 550965528936710154: 69 | to_leave = self.client.get_guild(int(id)) 70 | await ctx.send('Leaving ' + str(to_leave)) 71 | try: 72 | await to_leave.leave() 73 | await ctx.send('Left ' + str(to_leave)) 74 | except: 75 | await ctx.send('Failed leaving ' + str(to_leave)) 76 | return 77 | 78 | 79 | @commands.group(name='graph', aliases=['g']) 80 | async def graph(self, ctx): 81 | if ctx.invoked_subcommand is None: 82 | await ctx.invoke(self.ghelp) 83 | 84 | 85 | @graph.command(name='top10') 86 | async def graphtop10(self, ctx, arg2): 87 | if arg2 not in ['confirmed', 'active', 'deaths', 'recovered']: 88 | return 89 | 90 | newcountry = arg2.lower() 91 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/top_10_countries_' + \ 92 | newcountry + '.png' + '?' + str(uuid.uuid4().hex[:15]) 93 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 94 | description="Graph for Top 10 " + newcountry + 'Cases', color=0x00ff00) 95 | embedVar.set_footer( 96 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 97 | embedVar.set_image(url=urltobe) 98 | await ctx.send(embed=embedVar) 99 | 100 | 101 | @graph.command(name='country') 102 | async def graphcountry(self, ctx, arg2='all'): 103 | if arg2 == 'all': 104 | urltobe = 'https://github.com/resoucesforcorona/Resources/blob/master/All_countries.png?raw=true' 105 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 106 | description="Graph for all countries", color=0x00ff00) 107 | 108 | else: 109 | newcountry = (arg2.lower()).capitalize() 110 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/' + \ 111 | newcountry + '.png' + '?' + str(uuid.uuid4().hex[:15]) 112 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 113 | description="Graph for: " + newcountry, color=0x00ff00) 114 | 115 | embedVar.set_footer( 116 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 117 | embedVar.set_image(url=urltobe) 118 | await ctx.send(embed=embedVar) 119 | 120 | 121 | @graph.command(name='continent') 122 | async def graphcontinent(self, ctx, arg2='all'): 123 | if arg2 == 'all': 124 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/All_continents.png' 125 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 126 | description="Graph for all continents", color=0x00ff00) 127 | 128 | else: 129 | newcountry = (arg2.lower()).capitalize() 130 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/' + \ 131 | newcountry + '.png' + '?' + str(uuid.uuid4().hex[:15]) 132 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 133 | description="Graph for: " + newcountry, color=0x00ff00) 134 | 135 | embedVar.set_footer( 136 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 137 | embedVar.set_image(url=urltobe) 138 | await ctx.send(embed=embedVar) 139 | 140 | 141 | @graph.command(name='pie') 142 | async def graphpie(self, ctx): 143 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/all_countrywise_pie.png' 144 | embedVar = discord.Embed( 145 | title="Corona Tracker", url='https://anondoser.xyz', description="Graph for Pie", color=0x00ff00) 146 | embedVar.set_footer( 147 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 148 | embedVar.set_image(url=urltobe) 149 | await ctx.send(embed=embedVar) 150 | 151 | 152 | @graph.command(name='predict') 153 | async def predict(self, ctx, arg2): 154 | newcountry = (arg2.lower()) 155 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/world_prediction_curve_' + \ 156 | newcountry + '.png' + '?' + str(uuid.uuid4().hex[:15]) 157 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 158 | description="Graph for global prediction curve for " + newcountry, color=0x00ff00) 159 | embedVar.set_footer( 160 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 161 | embedVar.set_image(url=urltobe) 162 | await ctx.send(embed=embedVar) 163 | 164 | 165 | @graph.command(name='global') 166 | async def graphglobal(self, ctx, arg2): 167 | if arg2 not in ['daily_confirmed', 'daily_deaths', 'trend', 'deaths']: 168 | return 169 | 170 | if arg2 == 'daily_confirmed': 171 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/daily_confirmed_cases_global.png' 172 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 173 | description="Graph for global daily confirmed", color=0x00ff00) 174 | 175 | elif arg2 == 'daily_deaths': 176 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/daily_deaths_cases_global.png' 177 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 178 | description="Graph for global daily deaths", color=0x00ff00) 179 | 180 | elif arg2 == 'trend': 181 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/world_trend_confirmed_cases.png' 182 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 183 | description="Graph for global trend", color=0x00ff00) 184 | 185 | else: 186 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/worldwide_cases_deaths.png' 187 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 188 | description="Graph for global total deaths", color=0x00ff00) 189 | 190 | embedVar.set_footer( 191 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 192 | embedVar.set_image(url=urltobe) 193 | await ctx.send(embed=embedVar) 194 | 195 | 196 | @graph.command(name='trend') 197 | async def graphtrend(self, ctx, arg2): 198 | if arg2 not in ['confirmed', 'deaths']: 199 | return 200 | 201 | if arg2 == 'confirmed': 202 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/trend_comparison_continents_confirmed.png' 203 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 204 | description="Graph for trend comparison b/w continents [confirmed]", color=0x00ff00) 205 | 206 | else: 207 | newcountry = (arg2.lower()).capitalize() 208 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/trend_comparison_countries_deaths.png' 209 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 210 | description="Graph for trend comparison b/w countries [deaths]" + newcountry, color=0x00ff00) 211 | 212 | embedVar.set_footer( 213 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 214 | embedVar.set_image(url=urltobe) 215 | await ctx.send(embed=embedVar) 216 | 217 | 218 | @graph.command(name='spread') 219 | async def graphspread(self, ctx): 220 | urltobe = 'https://raw.githubusercontent.com/resoucesforcorona/Resources/master/countries_vs_date_spread.png' 221 | embedVar = discord.Embed(title="Corona Tracker", url='https://anondoser.xyz', 222 | description="Graph for number of countries infected vs date", color=0x00ff00) 223 | embedVar.set_footer( 224 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 225 | embedVar.set_image(url=urltobe) 226 | await ctx.send(embed=embedVar) 227 | 228 | 229 | @commands.command() 230 | async def help(self, ctx): 231 | embedVar = discord.Embed(title="Corona Tracker Help Panel", 232 | description="Here's some help for you :heart:", color=0x00ff00) 233 | embedVar.add_field( 234 | name="!cov graph [commands]", value="Consists of graphical predictions, analysis , statistics and more see below for command", inline=False) 235 | embedVar.add_field( 236 | name="!cov g [commands]", value="Same as above, use !cov ghelp for list of commands", inline=False) 237 | embedVar.add_field( 238 | name="!cov ghelp", value="Help and commands list for `!cov graph`", inline=False) 239 | embedVar.add_field( 240 | name="!cov all", value="Shows global Covid-19 statistics", inline=False) 241 | embedVar.add_field(name="!cov interactive", value="Sends the best live interactive maps \n See how the Covid spread on the world map from the very start \n See live status of Covid on the world map \n See Mortality Progression from the very beginning", inline=False) 242 | embedVar.add_field(name="!cov country {your country} {full/micro}", 243 | value="Shows you a particular country's stats (Optional- use 'micro' for a simplified report)", inline=False) 244 | embedVar.add_field( 245 | name="!cov help", value="Shows you this message", inline=False) 246 | embedVar.add_field( 247 | name="!cov invite", value="Sends you the links to invite the bot to your own server & the official bot server", inline=False) 248 | embedVar.add_field( 249 | name="github", value="https://github.com/himanshu2406/Corona-Tracker-Bot", inline=False) 250 | embedVar.add_field( 251 | name="tip :heart: ", value="Buy me a Coffee [sends addresses for tipping]", inline=False) 252 | embedVar.add_field(name="Dev Contact", 253 | value="Firelogger#7717", inline=False) 254 | await ctx.send(embed=embedVar) 255 | 256 | 257 | @commands.command() 258 | async def invite(self, ctx): 259 | embedVar = discord.Embed(title="Invite me", url='https://discord.com/api/oauth2/authorize?client_id=731855425145798668&permissions=121856&scope=bot', 260 | description="Click the title to invite to your own server", color=0x00ff00) 261 | embedVar.set_footer(text="Firelogger#7717", 262 | icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 263 | await ctx.send(embed=embedVar) 264 | 265 | 266 | @commands.command() 267 | async def tip(self, ctx): 268 | embedVar = discord.Embed(title="Tip :heart:", url='https://www.buymeacoffee.com/anondoser/shop', 269 | description="Donate for improving the services and help running the bot", color=0x00ff00) 270 | embedVar.add_field( 271 | name="Btc address", value="```37btgSzgWdywmSPeBN5rUH8W5G9EYJoRoA```", inline=False) 272 | embedVar.add_field( 273 | name="Paypal", value="```https://www.paypal.me/firelogger```", inline=False) 274 | embedVar.add_field( 275 | name="For more", value="For more methods please dm me", inline=False) 276 | embedVar.set_footer(text="Firelogger#7717", 277 | icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 278 | await ctx.send(embed=embedVar) 279 | 280 | 281 | @commands.command() 282 | async def interactive(self, ctx): 283 | embedVar = discord.Embed(title="Interactive and playable Maps and statistics", 284 | description="Play with these live maps , statistics and visuals", color=0x00ff00) 285 | embedVar.add_field(name="World Map Live Progression", 286 | value="See how COVID spread from the very beginning on the world map, seekable and playable", inline=False) 287 | embedVar.add_field( 288 | name="Link", value="https://corona.anondoser.xyz/worldmap_progression.html", inline=False) 289 | embedVar.add_field(name="World Map static interactive ", 290 | value="see the current spread of Covid-19 on the world map", inline=False) 291 | embedVar.add_field( 292 | name="Link", value="https://corona.anondoser.xyz/worldmap_cases_interactive.html", inline=False) 293 | embedVar.add_field(name="Mortality rate Live progression", 294 | value="A beautiful playable and seekable representation of the mortality rate progression from the beginning , see those balls bounce", inline=False) 295 | embedVar.add_field( 296 | name="Link", value="https://corona.anondoser.xyz/mortalityrate_progression.html", inline=False) 297 | embedVar.set_footer(text="Firelogger#7717", 298 | icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 299 | await ctx.send(embed=embedVar) 300 | 301 | 302 | @commands.command() 303 | async def ghelp(self, ctx): 304 | embedVar = discord.Embed(title="Corona Tracker graph commands ", 305 | description="Use - `!cov graph [command] [arguments]` you can use `!cov g` instead too", color=0x00ff00) 306 | embedVar.add_field(name="How to use - ", 307 | value="```!cov graph [commands given below] [argument]``` arguments in round brackets - () mean type exact commands as given , \n Square brackets -[] mean a variable like your country name", inline=False) 308 | embedVar.add_field( 309 | name="spread", value="No arguments ; shows the spread among countries vs date", inline=False) 310 | embedVar.add_field( 311 | name="pie", value="No arguments ; shows a list of pie charts for cases among countries", inline=False) 312 | embedVar.add_field(name="top10 (confirmed/active/deaths/recovered)", 313 | value="Shows top 10 countries based on the argument given", inline=False) 314 | embedVar.add_field(name="global (daily_confirmed/daily_deaths/trend/deaths)", 315 | value="Shows graphs for global arguments", inline=False) 316 | embedVar.add_field( 317 | name="country [country name]", value="Graph for the country given", inline=False) 318 | embedVar.add_field(name="continent [continent name]", 319 | value="Graph for the continent given", inline=False) 320 | embedVar.add_field(name="predict (confirmed/deaths)", 321 | value="Shows graphical projections for the future along with next 10 day predicted figures for the argument", inline=False) 322 | embedVar.add_field(name="trend (confirmed/deaths)", 323 | value="Shows trend between different countries / continents based on the argument", inline=False) 324 | #embedVar.add_field(name="github", value="https://github.com/himanshu2406/Corona-Tracker", inline=False) 325 | #embedVar.add_field(name="tip :heart: ", value="Buy me a Coffee [sends addresses for tipping]", inline=False) 326 | embedVar.add_field( 327 | name="Example", value="```!cov graph top10 confirmed```", inline=False) 328 | embedVar.set_footer(text="Firelogger#7717", 329 | icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 330 | await ctx.send(embed=embedVar) 331 | 332 | 333 | @commands.command(aliases=['c']) 334 | async def country(self, ctx, args, complete='full'): 335 | if complete not in ['full', 'micro']: 336 | return 337 | 338 | try: 339 | i = await self.api_client.country(args) 340 | yday_c = await self.api_client.country(i.name, yesterday=True) 341 | except diseaseapi.NotFound: 342 | embedVar = discord.Embed(title="Invalid Country: " + args.capitalize(), description="Error, the country doesn't exist in the database", color=0xe33b3b, url='https://anondoser.xyz') 343 | return await ctx.send(embed=embedVar) 344 | 345 | embedVar = discord.Embed(description="Statistics from disease.py", 346 | color=0xe33b3b, url='https://anondoser.xyz') 347 | 348 | yday_c = await self.api_client.country(i.name, yesterday=True) 349 | 350 | cases_diff = cleaned_diff(i.cases, yday_c.cases) 351 | death_diff = cleaned_diff(i.deaths, yday_c.deaths) 352 | re_diff = cleaned_diff(i.recoveries, yday_c.recoveries) 353 | active_diff = cleaned_diff(i.active, yday_c.active) 354 | crit_diff = cleaned_diff(i.critical, yday_c.critical) 355 | test_diff = cleaned_diff(i.tests, yday_c.tests) 356 | 357 | embedVar.add_field(name='Cases:', value=check_na(i.cases)+cases_diff, inline=True) 358 | embedVar.add_field(name='Cases Today:', value=check_na(i.today.cases), inline=True) 359 | embedVar.add_field(name='Deaths:', value=check_na(i.deaths)+death_diff, inline=True) 360 | embedVar.add_field(name='Deaths Today:', value=check_na(i.today.deaths), inline=True) 361 | embedVar.add_field(name='Recovered:', value=check_na(i.recoveries)+re_diff, inline=True) 362 | embedVar.add_field(name='Recovered Today:', value=check_na(i.today.recoveries), inline=True) 363 | embedVar.add_field(name='Active:', value=check_na(i.active)+active_diff, inline=True) 364 | embedVar.add_field(name='Critical:', value=check_na(i.critical)+crit_diff, inline=True) 365 | embedVar.add_field(name='Tests:', value=check_na(i.tests)+test_diff, inline=True) 366 | urltobe = str(i.info.flag) 367 | 368 | if complete == 'full': 369 | embedVar.add_field(name ='Cases per Million', value= i.per_million.cases, inline=True) 370 | embedVar.add_field(name ='Active per Million', value= i.per_million.active, inline=True) 371 | embedVar.add_field(name ='Recoveries per Million', value= i.per_million.recoveries, inline=True) 372 | embedVar.add_field(name ='Tests per Million', value= i.per_million.tests, inline=True) 373 | embedVar.add_field(name ='Deaths per Million', value= i.per_million.deaths, inline=True) 374 | embedVar.add_field(name ='Critical per Million', value= i.per_million.critical, inline=True) 375 | embedVar.add_field(name ='One Case per Person', value= i.per_people.case, inline=True) 376 | embedVar.add_field(name ='One Death per Person', value= i.per_people.death, inline=True) 377 | embedVar.add_field(name ='One Test per Person', value= i.per_people.test, inline=True) 378 | embedVar.add_field(name ='Updated', value= i.updated, inline=True) 379 | 380 | embedVar.title = "Covid Stats for: " + i.name 381 | embedVar.set_thumbnail(url=urltobe) 382 | embedVar.set_footer( 383 | text="Firelogger#7717", icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 384 | await ctx.send(embed=embedVar) 385 | 386 | 387 | @commands.command() 388 | async def all(self, ctx): 389 | response = await self.api_client.all() 390 | embedVar = discord.Embed(title="Covid Worldwide Stats", 391 | description="Statistics from disease.py", color=0xe33b3b, url='https://anondoser.xyz') 392 | 393 | 394 | yday_c = await self.api_client.all(yesterday=True) 395 | cases_diff = cleaned_diff(response.cases, yday_c.cases) 396 | death_diff = cleaned_diff(response.deaths, yday_c.deaths) 397 | re_diff = cleaned_diff(response.recoveries, yday_c.recoveries) 398 | active_diff = cleaned_diff(response.active, yday_c.active) 399 | crit_diff = cleaned_diff(response.critical, yday_c.critical) 400 | test_diff = cleaned_diff(response.tests, yday_c.tests) 401 | embedVar.add_field(name='Cases:', value=check_na(response.cases)+cases_diff, inline=True) 402 | embedVar.add_field(name='Cases Today:', value=check_na(response.today.cases), inline=True) 403 | embedVar.add_field(name='Deaths:', value=check_na(response.deaths)+death_diff, inline=True) 404 | embedVar.add_field(name='Deaths Today:', value=check_na(response.today.deaths), inline=True) 405 | embedVar.add_field(name='Recovered:', value=check_na(response.recoveries)+re_diff, inline=True) 406 | embedVar.add_field(name='Recovered Today:', value=check_na(response.today.recoveries), inline=True) 407 | embedVar.add_field(name='Active:', value=check_na(response.active)+active_diff, inline=True) 408 | embedVar.add_field(name='Critical:', value=check_na(response.critical)+crit_diff, inline=True) 409 | embedVar.add_field(name='Tests:', value=check_na(response.tests)+test_diff, inline=True) 410 | embedVar.add_field(name ='Cases per Million', value= response.per_million.cases, inline=True) 411 | embedVar.add_field(name ='Active per Million', value= response.per_million.active, inline=True) 412 | embedVar.add_field(name ='Recoveries per Million', value= response.per_million.recoveries, inline=True) 413 | embedVar.add_field(name ='Tests per Million', value= response.per_million.tests, inline=True) 414 | embedVar.add_field(name ='Deaths per Million', value= response.per_million.deaths, inline=True) 415 | embedVar.add_field(name ='Critical per Million', value= response.per_million.critical, inline=True) 416 | embedVar.add_field(name ='One Case per Person', value= response.per_people.case, inline=True) 417 | embedVar.add_field(name ='One Death per Person', value= response.per_people.death, inline=True) 418 | embedVar.add_field(name ='One Test per Person', value= response.per_people.test, inline=True) 419 | embedVar.add_field(name ='Updated', value= response.updated, inline=True) 420 | 421 | embedVar.set_footer(text="Firelogger#7717",icon_url='https://avatars2.githubusercontent.com/u/37951606?s=460&u=f45b1c7a7f0eddbe0036a7cf79b47d7dfa889321&v=4') 422 | await ctx.send(embed=embedVar) 423 | 424 | 425 | def setup(client): 426 | client.add_cog(CovidCommands(client)) -------------------------------------------------------------------------------- /Visualisations and Ai predictions/nb_og.py: -------------------------------------------------------------------------------- 1 | import pandas as pd 2 | import numpy as np 3 | import matplotlib.pyplot as plt 4 | from matplotlib import ticker 5 | import pycountry_convert as pc 6 | import folium 7 | import branca 8 | from datetime import datetime, timedelta,date 9 | from scipy.interpolate import make_interp_spline, BSpline 10 | import plotly.express as px 11 | import json, requests 12 | import calmap 13 | import urllib 14 | import base64 15 | from base64 import b64encode 16 | from keras.layers import Input, Dense, Activation, LeakyReLU, Dropout 17 | from keras import models 18 | from keras.optimizers import RMSprop, Adam 19 | 20 | import warnings 21 | warnings.filterwarnings('ignore') 22 | 23 | 24 | 25 | # Retriving Dataset 26 | 27 | while True: 28 | try: 29 | df_table = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/web-data/data/cases_time.csv",parse_dates=['Last_Update']) 30 | df_confirmed = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv') 31 | df_deaths = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_deaths_global.csv') 32 | 33 | # Depricated 34 | # df_recovered = pd.read_csv('https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-Recovered.csv') 35 | df_covid19 = pd.read_csv("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/web-data/data/cases_country.csv") 36 | except: 37 | continue 38 | else: 39 | break 40 | 41 | 42 | # new dataset 43 | df_covid19 = df_covid19.drop(["People_Tested","People_Hospitalized","UID","ISO3","Mortality_Rate"],axis =1) 44 | df_covid19.head(2) 45 | df_confirmed.head(2) 46 | 47 | df_confirmed = df_confirmed.rename(columns={"Province/State":"state","Country/Region": "country"}) 48 | df_deaths = df_deaths.rename(columns={"Province/State":"state","Country/Region": "country"}) 49 | df_covid19 = df_covid19.rename(columns={"Country_Region": "country"}) 50 | df_covid19["Active"] = df_covid19["Confirmed"]-df_covid19["Recovered"]-df_covid19["Deaths"] 51 | # df_recovered = df_recovered.rename(columns={"Province/State":"state","Country/Region": "country"}) 52 | df_confirmed.loc[df_confirmed['country'] == "US", "country"] = "USA" 53 | df_deaths.loc[df_deaths['country'] == "US", "country"] = "USA" 54 | df_covid19.loc[df_covid19['country'] == "US", "country"] = "USA" 55 | df_table.loc[df_table['Country_Region'] == "US", "Country_Region"] = "USA" 56 | # df_recovered.loc[df_recovered['country'] == "US", "country"] = "USA" 57 | 58 | 59 | df_confirmed.loc[df_confirmed['country'] == 'Korea, South', "country"] = 'South Korea' 60 | df_deaths.loc[df_deaths['country'] == 'Korea, South', "country"] = 'South Korea' 61 | df_covid19.loc[df_covid19['country'] == "Korea, South", "country"] = "South Korea" 62 | df_table.loc[df_table['Country_Region'] == "Korea, South", "Country_Region"] = "South Korea" 63 | # df_recovered.loc[df_recovered['country'] == 'Korea, South', "country"] = 'South Korea' 64 | 65 | df_confirmed.loc[df_confirmed['country'] == 'Taiwan*', "country"] = 'Taiwan' 66 | df_deaths.loc[df_deaths['country'] == 'Taiwan*', "country"] = 'Taiwan' 67 | df_covid19.loc[df_covid19['country'] == "Taiwan*", "country"] = "Taiwan" 68 | df_table.loc[df_table['Country_Region'] == "Taiwan*", "Country_Region"] = "Taiwan" 69 | # df_recovered.loc[df_recovered['country'] == 'Taiwan*', "country"] = 'Taiwan' 70 | 71 | df_confirmed.loc[df_confirmed['country'] == 'Congo (Kinshasa)', "country"] = 'Democratic Republic of the Congo' 72 | df_deaths.loc[df_deaths['country'] == 'Congo (Kinshasa)', "country"] = 'Democratic Republic of the Congo' 73 | df_covid19.loc[df_covid19['country'] == "Congo (Kinshasa)", "country"] = "Democratic Republic of the Congo" 74 | df_table.loc[df_table['Country_Region'] == "Congo (Kinshasa)", "Country_Region"] = "Democratic Republic of the Congo" 75 | # df_recovered.loc[df_recovered['country'] == 'Congo (Kinshasa)', "country"] = 'Democratic Republic of the Congo' 76 | 77 | df_confirmed.loc[df_confirmed['country'] == "Cote d'Ivoire", "country"] = "Côte d'Ivoire" 78 | df_deaths.loc[df_deaths['country'] == "Cote d'Ivoire", "country"] = "Côte d'Ivoire" 79 | df_covid19.loc[df_covid19['country'] == "Cote d'Ivoire", "country"] = "Côte d'Ivoire" 80 | df_table.loc[df_table['Country_Region'] == "Cote d'Ivoire", "Country_Region"] = "Côte d'Ivoire" 81 | # df_recovered.loc[df_recovered['country'] == "Cote d'Ivoire", "country"] = "Côte d'Ivoire" 82 | 83 | df_confirmed.loc[df_confirmed['country'] == "Reunion", "country"] = "Réunion" 84 | df_deaths.loc[df_deaths['country'] == "Reunion", "country"] = "Réunion" 85 | df_covid19.loc[df_covid19['country'] == "Reunion", "country"] = "Réunion" 86 | df_table.loc[df_table['Country_Region'] == "Reunion", "Country_Region"] = "Réunion" 87 | # df_recovered.loc[df_recovered['country'] == "Reunion", "country"] = "Réunion" 88 | 89 | df_confirmed.loc[df_confirmed['country'] == 'Congo (Brazzaville)', "country"] = 'Republic of the Congo' 90 | df_deaths.loc[df_deaths['country'] == 'Congo (Brazzaville)', "country"] = 'Republic of the Congo' 91 | df_covid19.loc[df_covid19['country'] == "Congo (Brazzaville)", "country"] = "Republic of the Congo" 92 | df_table.loc[df_table['Country_Region'] == "Congo (Brazzaville)", "Country_Region"] = "Republic of the Congo" 93 | # df_recovered.loc[df_recovered['country'] == 'Congo (Brazzaville)', "country"] = 'Republic of the Congo' 94 | 95 | df_confirmed.loc[df_confirmed['country'] == 'Bahamas, The', "country"] = 'Bahamas' 96 | df_deaths.loc[df_deaths['country'] == 'Bahamas, The', "country"] = 'Bahamas' 97 | df_covid19.loc[df_covid19['country'] == "Bahamas, The", "country"] = "Bahamas" 98 | df_table.loc[df_table['Country_Region'] == "Bahamas, The", "Country_Region"] = "Bahamas" 99 | # df_recovered.loc[df_recovered['country'] == 'Bahamas, The', "country"] = 'Bahamas' 100 | 101 | df_confirmed.loc[df_confirmed['country'] == 'Gambia, The', "country"] = 'Gambia' 102 | df_deaths.loc[df_deaths['country'] == 'Gambia, The', "country"] = 'Gambia' 103 | df_covid19.loc[df_covid19['country'] == "Gambia, The", "country"] = "Gambia" 104 | df_table.loc[df_table['Country_Region'] == "Gambia", "Country_Region"] = "Gambia" 105 | # df_recovered.loc[df_recovered['country'] == 'Gambia, The', "country"] = 'Gambia' 106 | 107 | # getting all countries 108 | countries = np.asarray(df_confirmed["country"]) 109 | countries1 = np.asarray(df_covid19["country"]) 110 | # Continent_code to Continent_names 111 | continents = { 112 | 'NA': 'North America', 113 | 'SA': 'South America', 114 | 'AS': 'Asia', 115 | 'OC': 'Australia', 116 | 'AF': 'Africa', 117 | 'EU' : 'Europe', 118 | 'na' : 'Others' 119 | } 120 | 121 | # Defininng Function for getting continent code for country. 122 | def country_to_continent_code(country): 123 | try: 124 | return pc.country_alpha2_to_continent_code(pc.country_name_to_country_alpha2(country)) 125 | except : 126 | return 'na' 127 | 128 | #Collecting Continent Information 129 | df_confirmed.insert(2,"continent", [continents[country_to_continent_code(country)] for country in countries[:]]) 130 | df_deaths.insert(2,"continent", [continents[country_to_continent_code(country)] for country in countries[:]]) 131 | df_covid19.insert(1,"continent", [continents[country_to_continent_code(country)] for country in countries1[:]]) 132 | df_table.insert(1,"continent", [continents[country_to_continent_code(country)] for country in df_table["Country_Region"].values]) 133 | # df_recovered.insert(2,"continent", [continents[country_to_continent_code(country)] for country in countries[:]] ) 134 | 135 | df_table = df_table[df_table["continent"] != "Others"] 136 | 137 | df_deaths[df_deaths["continent" ]== 'Others'] 138 | 139 | df_confirmed = df_confirmed.replace(np.nan, '', regex=True) 140 | df_deaths = df_deaths.replace(np.nan, '', regex=True) 141 | # df_recovered = df_recovered.replace(np.nan, '', regex=True) 142 | # df_active = df_active.replace(np.nan, '', regex=True) 143 | 144 | """# FUNCTIONS BELOW HERE""" 145 | 146 | def plot_params(ax,axis_label= None, plt_title = None,label_size=15, axis_fsize = 15, title_fsize = 20, scale = 'linear' ): 147 | # Tick-Parameters 148 | ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) 149 | ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) 150 | ax.tick_params(which='both', width=1,labelsize=label_size) 151 | ax.tick_params(which='major', length=6) 152 | ax.tick_params(which='minor', length=3, color='0.8') 153 | 154 | # Grid 155 | plt.grid(lw = 1, ls = '-', c = "0.7", which = 'major') 156 | plt.grid(lw = 1, ls = '-', c = "0.9", which = 'minor') 157 | 158 | # Plot Title 159 | plt.title( plt_title,{'fontsize':title_fsize}) 160 | 161 | # Yaxis sacle 162 | plt.yscale(scale) 163 | plt.minorticks_on() 164 | # Plot Axes Labels 165 | xl = plt.xlabel(axis_label[0],fontsize = axis_fsize) 166 | yl = plt.ylabel(axis_label[1],fontsize = axis_fsize) 167 | 168 | def visualize_covid_cases(confirmed, deaths, continent=None , country = None , state = None, period = None, figure = None, scale = "linear"): 169 | x = 0 170 | if figure == None: 171 | f = plt.figure(figsize=(10,10)) 172 | # Sub plot 173 | ax = f.add_subplot(111) 174 | else : 175 | f = figure[0] 176 | # Sub plot 177 | ax = f.add_subplot(figure[1],figure[2],figure[3]) 178 | ax.set_axisbelow(True) 179 | plt.tight_layout(pad=10, w_pad=5, h_pad=5) 180 | 181 | stats = [confirmed, deaths] 182 | label = ["Confirmed", "Deaths"] 183 | 184 | if continent != None: 185 | params = ["continent",continent] 186 | elif country != None: 187 | params = ["country",country] 188 | else: 189 | params = ["All", "All"] 190 | color = ["darkcyan","crimson"] 191 | marker_style = dict(linewidth=3, linestyle='-', marker='o',markersize=4, markerfacecolor='#ffffff') 192 | for i,stat in enumerate(stats): 193 | if params[1] == "All" : 194 | cases = np.sum(np.asarray(stat.iloc[:,5:]),axis = 0)[x:] 195 | else : 196 | cases = np.sum(np.asarray(stat[stat[params[0]] == params[1]].iloc[:,5:]),axis = 0)[x:] 197 | date = np.arange(1,cases.shape[0]+1)[x:] 198 | plt.plot(date,cases,label = label[i]+" (Total : "+str(cases[-1])+")",color=color[i],**marker_style) 199 | plt.fill_between(date,cases,color=color[i],alpha=0.3) 200 | 201 | if params[1] == "All" : 202 | Total_confirmed = np.sum(np.asarray(stats[0].iloc[:,5:]),axis = 0)[x:] 203 | Total_deaths = np.sum(np.asarray(stats[1].iloc[:,5:]),axis = 0)[x:] 204 | else : 205 | Total_confirmed = np.sum(np.asarray(stats[0][stat[params[0]] == params[1]].iloc[:,5:]),axis = 0)[x:] 206 | Total_deaths = np.sum(np.asarray(stats[1][stat[params[0]] == params[1]].iloc[:,5:]),axis = 0)[x:] 207 | 208 | text = "From "+stats[0].columns[5]+" to "+stats[0].columns[-1]+"\n" 209 | text += "Mortality rate : "+ str(int(Total_deaths[-1]/(Total_confirmed[-1])*10000)/100)+"\n" 210 | text += "Last 5 Days:\n" 211 | text += "Confirmed : " + str(Total_confirmed[-1] - Total_confirmed[-6])+"\n" 212 | text += "Deaths : " + str(Total_deaths[-1] - Total_deaths[-6])+"\n" 213 | text += "Last 24 Hours:\n" 214 | text += "Confirmed : " + str(Total_confirmed[-1] - Total_confirmed[-2])+"\n" 215 | text += "Deaths : " + str(Total_deaths[-1] - Total_deaths[-2])+"\n" 216 | 217 | plt.text(0.02, 0.78, text, fontsize=15, horizontalalignment='left', verticalalignment='top', transform=ax.transAxes,bbox=dict(facecolor='white', alpha=0.4)) 218 | 219 | # Plot Axes Labels 220 | axis_label = ["Days ("+df_confirmed.columns[5]+" - "+df_confirmed.columns[-1]+")","No of Cases"] 221 | 222 | # Plot Parameters 223 | plot_params(ax,axis_label,scale = scale) 224 | 225 | # Plot Title 226 | if params[1] == "All" : 227 | plt.title("COVID-19 Cases World",{'fontsize':25}) 228 | else: 229 | plt.title("COVID-19: "+params[1] ,{'fontsize':25}) 230 | 231 | # Legend Location 232 | l = plt.legend(loc= "best",fontsize = 15) 233 | 234 | if figure == None: 235 | #plt.show() 236 | pass 237 | 238 | def get_total_cases(cases, country = "All"): 239 | if(country == "All") : 240 | return np.sum(np.asarray(cases.iloc[:,5:]),axis = 0)[-1] 241 | else : 242 | return np.sum(np.asarray(cases[cases["country"] == country].iloc[:,5:]),axis = 0)[-1] 243 | 244 | def get_mortality_rate(confirmed,deaths, continent = None, country = None): 245 | if continent != None: 246 | params = ["continent",continent] 247 | elif country != None: 248 | params = ["country",country] 249 | else : 250 | params = ["All", "All"] 251 | 252 | if params[1] == "All" : 253 | Total_confirmed = np.sum(np.asarray(confirmed.iloc[:,5:]),axis = 0) 254 | Total_deaths = np.sum(np.asarray(deaths.iloc[:,5:]),axis = 0) 255 | mortality_rate = np.round((Total_deaths/(Total_confirmed+1.01))*100,2) 256 | else : 257 | Total_confirmed = np.sum(np.asarray(confirmed[confirmed[params[0]] == params[1]].iloc[:,5:]),axis = 0) 258 | Total_deaths = np.sum(np.asarray(deaths[deaths[params[0]] == params[1]].iloc[:,5:]),axis = 0) 259 | mortality_rate = np.round((Total_deaths/(Total_confirmed+1.01))*100,2) 260 | 261 | return np.nan_to_num(mortality_rate) 262 | def dd(date1,date2): 263 | return (datetime.strptime(date1,'%m/%d/%y') - datetime.strptime(date2,'%m/%d/%y')).days 264 | 265 | 266 | out = ""#+"output/" 267 | 268 | df_countries_cases = df_covid19.copy().drop(['Lat','Long_','continent','Last_Update'],axis =1) 269 | df_countries_cases.index = df_countries_cases["country"] 270 | df_countries_cases = df_countries_cases.drop(['country'],axis=1) 271 | 272 | df_continents_cases = df_covid19.copy().drop(['Lat','Long_','country','Last_Update'],axis =1) 273 | df_continents_cases = df_continents_cases.groupby(["continent"]).sum() 274 | 275 | df_countries_cases.fillna(0,inplace=True) 276 | df_continents_cases.fillna(0,inplace=True) 277 | 278 | 279 | 280 | f = plt.figure(figsize=(10,5)) 281 | f.add_subplot(111) 282 | 283 | plt.axes(axisbelow=True) 284 | plt.barh(df_countries_cases.sort_values('Confirmed')["Confirmed"].index[-10:],df_countries_cases.sort_values('Confirmed')["Confirmed"].values[-10:],color="darkcyan") 285 | plt.tick_params(size=5,labelsize = 13) 286 | plt.xlabel("Confirmed Cases",fontsize=18) 287 | plt.title("Top 10 Countries (Confirmed Cases)",fontsize=20) 288 | plt.grid(alpha=0.3) 289 | plt.savefig(out+'top_10_countries_confirmed.png') 290 | 291 | 292 | f = plt.figure(figsize=(10,5)) 293 | f.add_subplot(111) 294 | 295 | plt.axes(axisbelow=True) 296 | plt.barh(df_countries_cases.sort_values('Deaths')["Deaths"].index[-10:],df_countries_cases.sort_values('Deaths')["Deaths"].values[-10:],color="crimson") 297 | plt.tick_params(size=5,labelsize = 13) 298 | plt.xlabel("Deaths Cases",fontsize=18) 299 | plt.title("Top 10 Countries (Deaths Cases)",fontsize=20) 300 | plt.grid(alpha=0.3,which='both') 301 | plt.savefig(out+'top_10_countries_deaths.png') 302 | 303 | 304 | 305 | f = plt.figure(figsize=(10,5)) 306 | f.add_subplot(111) 307 | 308 | plt.axes(axisbelow=True) 309 | plt.barh(df_countries_cases.sort_values('Active')["Active"].index[-10:],df_countries_cases.sort_values('Active')["Active"].values[-10:],color="darkorange") 310 | plt.tick_params(size=5,labelsize = 13) 311 | plt.xlabel("Active Cases",fontsize=18) 312 | plt.title("Top 10 Countries (Active Cases)",fontsize=20) 313 | plt.grid(alpha=0.3,which='both') 314 | plt.savefig(out+'top_10_countries_active.png') 315 | 316 | 317 | 318 | f = plt.figure(figsize=(10,5)) 319 | f.add_subplot(111) 320 | 321 | plt.axes(axisbelow=True) 322 | plt.barh(df_countries_cases.sort_values('Recovered')["Recovered"].index[-10:],df_countries_cases.sort_values('Recovered')["Recovered"].values[-10:],color="limegreen") 323 | plt.tick_params(size=5,labelsize = 13) 324 | plt.xlabel("Recovered Cases",fontsize=18) 325 | plt.title("Top 10 Countries (Recovered Cases)",fontsize=20) 326 | plt.grid(alpha=0.3,which='both') 327 | plt.savefig(out+'top_10_countries_recovered.png') 328 | 329 | 330 | world_map = folium.Map(location=[10,0], tiles="cartodbpositron", zoom_start=2,max_zoom=6,min_zoom=2) 331 | for i in range(0,len(df_confirmed)): 332 | folium.Circle( 333 | location=[df_confirmed.iloc[i]['Lat'], df_confirmed.iloc[i]['Long']], 334 | tooltip = "
"+df_confirmed.iloc[i]['country']+"
"+ 335 | "
"+str(np.nan_to_num(df_confirmed.iloc[i]['state']))+"
"+ 336 | "
"+ 337 | "" 343 | , 344 | radius=(int((np.log(df_confirmed.iloc[i,-1]+1.00001)))+0.2)*50000, 345 | color='#ff6600', 346 | fill_color='#ff8533', 347 | fill=True).add_to(world_map) 348 | 349 | #world_map 350 | world_map.save('worldmap_cases_interactive.html') 351 | 352 | df_data = df_table.groupby(['Last_Update', 'Country_Region'])['Confirmed', 'Deaths'].max().reset_index().fillna(0) 353 | df_data["Last_Update"] = pd.to_datetime( df_data["Last_Update"]).dt.strftime('%m/%d/%Y') 354 | 355 | fig = px.scatter_geo(df_data, locations="Country_Region", locationmode='country names', 356 | color=np.power(df_data["Confirmed"],0.3)-2 , size= np.power(df_data["Confirmed"]+1,0.3)-1, hover_name="Country_Region", 357 | hover_data=["Confirmed"], 358 | range_color= [0, max(np.power(df_data["Confirmed"],0.3))], 359 | projection="natural earth", animation_frame="Last_Update", 360 | color_continuous_scale=px.colors.sequential.Plasma, 361 | title='COVID-19: Progression of spread - corona.anondoser.xyz' 362 | ) 363 | fig.update_coloraxes(colorscale="hot") 364 | fig.update(layout_coloraxis_showscale=False) 365 | fig.write_html("worldmap_progression.html") 366 | 367 | case_nums_country = df_confirmed.groupby("country").sum().drop(['Lat','Long'],axis =1).apply(lambda x: x[x > 0].count(), axis =0) 368 | d = [datetime.strptime(date,'%m/%d/%y').strftime("%d %b") for date in case_nums_country.index] 369 | 370 | f = plt.figure(figsize=(15,8)) 371 | f.add_subplot(111) 372 | marker_style = dict(c="crimson",linewidth=6, linestyle='-', marker='o',markersize=8, markerfacecolor='#ffffff') 373 | plt.plot(d, case_nums_country,**marker_style) 374 | plt.tick_params(labelsize = 14) 375 | plt.xticks(list(np.arange(0,len(d),int(len(d)/5))),d[:-1:int(len(d)/5)]+[d[-1]]) 376 | 377 | #labels 378 | plt.xlabel("Dates",fontsize=18) 379 | plt.ylabel("Number of Countries/Regions",fontsize=1) 380 | plt.grid(alpha = 0.3) 381 | 382 | plt.savefig(out+'countries_vs_date_spread.png') 383 | plt.close() 384 | 385 | 386 | cols = 1 387 | rows = 1 388 | f = plt.figure(figsize=(10,10*rows)) 389 | 390 | visualize_covid_cases(df_confirmed, df_deaths,continent = "All",figure = [f,rows,cols, 1]) 391 | 392 | plt.savefig(out+'worldwide_cases_deaths.png') 393 | 394 | 395 | 396 | df_continents= df_confirmed.groupby(["continent"]).sum() 397 | continents = df_continents.sort_values(df_continents.columns[-1],ascending = False).index 398 | 399 | cols =2 400 | rows = int(np.ceil(continents.shape[0]/cols)) 401 | f = plt.figure(figsize=(20,9*rows)) 402 | for i,continent in enumerate(continents): 403 | visualize_covid_cases(df_confirmed, df_deaths, continent = continent,figure = [f,rows,cols, i+1]) 404 | #plt.savefig(out+continent + '.png') 405 | 406 | #plt.show() 407 | plt.savefig(out+'All_continents.png') 408 | 409 | 410 | 411 | df_continents= df_confirmed.groupby(["continent"]).sum() 412 | continents = df_continents.sort_values(df_continents.columns[-1],ascending = False).index 413 | 414 | 415 | cols =1 416 | rows = 1 417 | #f = plt.figure(figsize=(10,10*rows)) 418 | continentdict = {} 419 | for i,continent in enumerate(continents): 420 | f = plt.figure(figsize=(10,10*rows)) 421 | visualize_covid_cases(df_confirmed, df_deaths, continent = continent,figure = [f,rows,cols, 1]) 422 | #visualize_covid_cases(df_confirmed, df_deaths, continent = continent,figure = [f,1,1, 1]) 423 | namee = continent.lower() 424 | plt.savefig(out+namee + '.png') 425 | 426 | 427 | df_countries = df_confirmed.groupby(["country"]).sum() 428 | df_countries = df_countries.sort_values(df_countries.columns[-1],ascending = False) 429 | countries = df_countries[df_countries[df_countries.columns[-1]] >= 15000].index 430 | 431 | cols =2 432 | rows = int(np.ceil(countries.shape[0]/cols)) 433 | f = plt.figure(figsize=(18,7*rows)) 434 | for i,country in enumerate(countries): 435 | visualize_covid_cases(df_confirmed, df_deaths,country = country,figure = [f,rows,cols, i+1]) 436 | #plt.savefig(out+country + '.png') 437 | 438 | #plt.show() 439 | plt.savefig('All_countries.png') 440 | 441 | 442 | 443 | df_continents= df_confirmed.groupby(["continent"]).sum() 444 | continents = df_continents.sort_values(df_continents.columns[-1],ascending = False).index 445 | 446 | df_countries = df_confirmed.groupby(["country"]).sum() 447 | df_countries = df_countries.sort_values(df_countries.columns[-1],ascending = False) 448 | countries = df_countries[df_countries[df_countries.columns[-1]] >= 15000].index 449 | 450 | cols =1 451 | rows = 1 452 | countrydict = {} 453 | 454 | for i,country in enumerate(countries): 455 | f = plt.figure(figsize=(10,10*rows)) 456 | visualize_covid_cases(df_confirmed, df_deaths,country = country,figure = [f,rows,cols, 1]) 457 | namee = country.lower() 458 | plt.savefig(out+namee + '.png') 459 | 460 | 461 | #plt.show() 462 | #plt.savefig('All_countries.png') 463 | 464 | 465 | 466 | temp = df_deaths.groupby('country').sum().drop(["Lat","Long"],axis =1).sort_values(df_deaths.columns[-1], ascending= False) 467 | 468 | threshold = 10 469 | f = plt.figure(figsize=(15,12)) 470 | ax = f.add_subplot(111) 471 | for i,country in enumerate(temp.index): 472 | if i >= 10: 473 | break 474 | days = 61 475 | t = temp.loc[temp.index== country].values[0] 476 | t = t[t>threshold][:days] 477 | 478 | date = np.arange(0,len(t[:days])) 479 | xnew = np.linspace(date.min(), date.max(), 30) 480 | spl = make_interp_spline(date, t, k=1) # type: BSpline 481 | power_smooth = spl(xnew) 482 | plt.plot(xnew,power_smooth,'-o',label = country,linewidth =3, markevery=[-1]) 483 | 484 | 485 | plt.tick_params(labelsize = 14) 486 | plt.xticks(np.arange(0,days,7),[ "Day "+str(i) for i in range(days)][::7]) 487 | 488 | # Reference lines 489 | x = np.arange(0,18) 490 | y = 2**(x+np.log2(threshold)) 491 | plt.plot(x,y,"--",linewidth =2,color = "gray") 492 | plt.annotate("No. of cases doubles every day",(x[-2],y[-1]),xycoords="data",fontsize=14,alpha = 0.5) 493 | 494 | x = np.arange(0,days-22) 495 | y = 2**(x/2+np.log2(threshold)) 496 | plt.plot(x,y,"--",linewidth =2,color = "gray") 497 | plt.annotate(".. every second day",(x[-3],y[-1]),xycoords="data",fontsize=14,alpha = 0.5) 498 | 499 | x = np.arange(0,days-3) 500 | y = 2**(x/7+np.log2(threshold)) 501 | plt.plot(x,y,"--",linewidth =2,color = "gray") 502 | plt.annotate(".. every week",(x[-3],y[-1]),xycoords="data",fontsize=14,alpha = 0.5) 503 | 504 | x = np.arange(0,days-3) 505 | y = 2**(x/30+np.log2(threshold)) 506 | plt.plot(x,y,"--",linewidth =2,color = "gray") 507 | plt.annotate(".. every month",(x[-3],y[-1]),xycoords="data",fontsize=14,alpha = 0.5) 508 | 509 | # plot Params 510 | plt.xlabel("Days",fontsize=17) 511 | plt.ylabel("Number of Deaths",fontsize=17) 512 | plt.title("Trend Comparison of Different Countries \n(Deaths)",fontsize=22) 513 | plt.legend(loc = "upper left") 514 | plt.yscale("log") 515 | plt.grid(which="both") 516 | plt.savefig(out+'trend_comparison_countries_deaths.png') 517 | #plt.show() 518 | 519 | 520 | 521 | 522 | temp = df_confirmed.groupby('continent').sum().drop(["Lat","Long"],axis =1).sort_values(df_confirmed.columns[-1], ascending= False) 523 | 524 | threshold = 50 525 | f = plt.figure(figsize=(15,12)) 526 | ax = f.add_subplot(111) 527 | for i,country in enumerate(temp.index): 528 | if i >= 10: 529 | break 530 | days = 61 531 | t = temp.loc[temp.index== country].values[0] 532 | t = t[t>threshold][:days] 533 | 534 | date = np.arange(0,len(t[:days])) 535 | xnew = np.linspace(date.min(), date.max(), 30) 536 | spl = make_interp_spline(date, t, k=1) # type: BSpline 537 | power_smooth = spl(xnew) 538 | plt.plot(xnew,power_smooth,'-o',label = country,linewidth =3, markevery=[-1]) 539 | 540 | plt.tick_params(labelsize = 14) 541 | plt.xticks(np.arange(0,days,7),[ "Day "+str(i) for i in range(days)][::7]) 542 | 543 | # Reference lines 544 | x = np.arange(0,18) 545 | y = 2**(x+np.log2(threshold)) 546 | plt.plot(x,y,"--",linewidth =2,color = "gray") 547 | plt.annotate("No. of cases doubles every day",(x[-2],y[-1]),xycoords="data",fontsize=14,alpha = 0.5) 548 | 549 | x = np.arange(0,days-22) 550 | y = 2**(x/2+np.log2(threshold)) 551 | plt.plot(x,y,"--",linewidth =2,color = "gray") 552 | plt.annotate(".. every second day",(x[-3],y[-1]),xycoords="data",fontsize=14,alpha = 0.5) 553 | 554 | x = np.arange(0,days-2) 555 | y = 2**(x/7+np.log2(threshold)) 556 | plt.plot(x,y,"--",linewidth =2,color = "gray") 557 | plt.annotate(".. every week",(x[-3],y[-1]),xycoords="data",fontsize=14,alpha = 0.5) 558 | 559 | x = np.arange(0,days-3) 560 | y = 2**(x/30+np.log2(threshold)) 561 | plt.plot(x,y,"--",linewidth =2,color = "gray") 562 | plt.annotate(".. every month",(x[-3],y[-1]),xycoords="data",fontsize=14,alpha = 0.5) 563 | 564 | 565 | # plot Params 566 | plt.xlabel("Days",fontsize=17) 567 | plt.ylabel("Number of Confirmed Cases",fontsize=17) 568 | plt.title("Trend Comparison of Different Continents \n(confirmed) ",fontsize=22) 569 | plt.legend(loc = "upper left") 570 | plt.yscale("log") 571 | plt.grid(which="both") 572 | plt.savefig(out+'trend_comparison_continents_confirmed.png') 573 | #plt.show() 574 | 575 | 576 | 577 | 578 | temp_data = df_confirmed.iloc[:,5:].sum(axis =0) 579 | f = plt.figure(figsize=(20,12)) 580 | f.add_subplot(111) 581 | 582 | threshold = 100000 583 | 584 | t = temp_data.values 585 | t = t[t >threshold] 586 | 587 | date = np.arange(0,len(t[:])) 588 | xnew = np.linspace(date.min(), date.max(), 10) 589 | spl = make_interp_spline(date, t, k=1) # type: BSpline 590 | power_smooth = spl(xnew) 591 | 592 | marker_style = dict(linewidth=4, linestyle='-', marker='o',markersize=10, markerfacecolor='#ffffff') 593 | plt.plot(date,t,"-.",label="Confirmed Cases",**marker_style) 594 | 595 | days = 150 596 | # Reference lines 597 | x = np.arange(0,days) 598 | y = 2**(x+np.log2(threshold)) 599 | plt.plot(x,y,"--",linewidth =1,color = "gray") 600 | plt.annotate("No. of Cases Doubles Every Day",(np.log2((t.max()-threshold)/threshold),t.max()-threshold/2),xycoords="data",fontsize=14,alpha = 0.5) 601 | 602 | x = np.arange(0,days) 603 | y = 2**(x/3+np.log2(threshold)) 604 | plt.plot(x,y,"--",linewidth =1,color = "gray") 605 | plt.annotate("...Every Third Day",(np.log2((t.max()-threshold)/threshold)*3,(t.max()/1.2)-threshold/2),xycoords="data",fontsize=14,alpha = 0.5) 606 | 607 | x = np.arange(0,days) 608 | y = 2**(x/7+np.log2(threshold)) 609 | plt.plot(x,y,"--",linewidth =1,color = "gray") 610 | plt.annotate("... Every Week",(np.log2((t.max()-threshold)/threshold)*7,t.max()-threshold),xycoords="data",fontsize=14,alpha = 0.5) 611 | 612 | x = np.arange(0,days) 613 | y = 2**(x/30+np.log2(threshold)) 614 | plt.plot(x,y,"--",linewidth =1,color = "gray") 615 | plt.annotate(".. Every Month",(len(t)-25,2**((len(t)-25)/30+np.log2(threshold))),xycoords="data",fontsize=14,alpha = 0.5) 616 | 617 | x = np.arange(0,days) 618 | y = 2**(x/13+np.log2(threshold)) 619 | plt.plot(x,y,"--",linewidth =1,color = "Red") 620 | plt.annotate(".. Every 13 Days",(np.log2((t.max()-threshold)/threshold)*13,t.max()-threshold),color="Red",xycoords="data",fontsize=14,alpha = 0.8) 621 | 622 | 623 | plt.xlim(date[0],date[-1]) 624 | plt.ylim(threshold - threshold/10,2*t.max()) 625 | # plot Params 626 | # plt.tight_layout() 627 | plt.tick_params(labelsize = 16) 628 | plt.xticks(np.arange(0,len(t[:])+10,10),[ "Day "+str(i) for i in range(len(t[:])+10)][::10]) 629 | plt.xlabel("Days",fontsize=19) 630 | plt.ylabel("Number of Confirmed Cases",fontsize=19) 631 | plt.title("World Trend",fontsize=24) 632 | plt.legend(loc = "upper left") 633 | plt.yscale("log") 634 | plt.grid(which="both") 635 | plt.savefig(out+"world_trend_confirmed_cases.png") 636 | #plt.show() 637 | 638 | 639 | 640 | data_y = np.log10(np.asarray(df_confirmed.iloc[:,5:].sum(axis =0)).astype("float32")) 641 | data_x = np.arange(1,len(data_y)+1) 642 | 643 | model = models.load_model("model_confirmed_v4.h5") 644 | #model.summary() 645 | 646 | lakh = 100000 647 | prediction_days = 10 648 | 649 | temp_data = df_confirmed.iloc[:,5:].sum(axis =0) 650 | data = np.power(10,model.predict(np.arange(1,len(temp_data)+prediction_days+1))) 651 | f = plt.figure(figsize=(15,10)) 652 | ax = f.add_subplot(111) 653 | 654 | date = np.arange(0,len(temp_data)) 655 | 656 | marker_style = dict(linewidth=3, linestyle='-', marker='o',markersize=7, markerfacecolor='#ffffff') 657 | plt.plot(date,temp_data/lakh,"-.",color="darkcyan",**marker_style, label="Actual Curve") 658 | 659 | date = np.arange(0,len(data)) 660 | plt.plot(date,data/lakh,"-.",color="orangered",label="Predicted Curve") 661 | 662 | nextdays = [(datetime.strptime(d[-1],'%d %b')+timedelta(days=i)).strftime("%d %b") for i in range(1,prediction_days+1)] 663 | total = d + nextdays 664 | 665 | text = "Prediction for next "+str(prediction_days) +" days:\n" 666 | for i in range(prediction_days): 667 | text += nextdays[i]+" : "+str(np.round(data[-1*(prediction_days-i)],-3)[0]/lakh)+" L\n" 668 | 669 | plt.text(0.02, 0.78, text, fontsize=17, horizontalalignment='left', verticalalignment='top', transform=ax.transAxes,bbox=dict(facecolor='white', alpha=0.4)) 670 | 671 | # X-axis 672 | plt.xticks(list(np.arange(0,len(total),int(len(total)/5))),total[:-1:int(len(total)/5)]+[total[-1]]) 673 | 674 | # Tick-Parameters 675 | ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) 676 | ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) 677 | ax.tick_params(which='both', width=1,labelsize=14) 678 | ax.tick_params(which='major', length=6) 679 | ax.tick_params(which='minor', length=3, color='0.8') 680 | 681 | # Grid 682 | plt.grid(lw = 1, ls = '-', c = "0.7", which = 'major') 683 | plt.grid(lw = 1, ls = '-', c = "0.9", which = 'minor') 684 | 685 | # Plot Title 686 | plt.title("COVID-19 Next 10 day Prediction Curve-Global Confirmed Cases",{'fontsize':22}) 687 | 688 | # Axis Lable 689 | plt.xlabel("Date",fontsize =18) 690 | plt.ylabel("Number of Confirmed Cases (Lakh)",fontsize =18) 691 | 692 | # plt.yscale("log") 693 | plt.legend(fontsize =18) 694 | plt.tick_params(labelsize = 13) 695 | plt.savefig(out+"world_prediction_curve_confirmed.png") 696 | #plt.show() 697 | 698 | 699 | 700 | data1_y = np.log10(np.asarray(df_deaths.iloc[:,5:].sum(axis =0)).astype("float32")) 701 | data1_x = np.arange(1,len(data1_y)+1) 702 | 703 | model2 = models.load_model("model_deaths_v5.h5") 704 | #model2.summary() 705 | 706 | thousand = 1000 707 | prediction_days = 10 708 | 709 | temp_data = df_deaths.iloc[:,5:].sum(axis =0) 710 | data = np.power(10,model2.predict(np.arange(1,len(temp_data)+prediction_days+1))) 711 | f = plt.figure(figsize=(15,10)) 712 | ax = f.add_subplot(111) 713 | 714 | 715 | date = np.arange(0,len(temp_data)) 716 | # xnew = np.linspace(date.min(), date.max(), 10) 717 | # spl = make_interp_spline(date, t, k=1) # type: BSpline 718 | # power_smooth = spl(xnew) 719 | 720 | marker_style = dict(linewidth=3, linestyle='-', marker='o',markersize=7, markerfacecolor='#ffffff') 721 | plt.plot(date,temp_data/thousand,"-.",color="maroon",**marker_style, label="Actual Curve") 722 | 723 | date = np.arange(0,len(data)) 724 | plt.plot(date,data/thousand,"-.",color="orangered",label="Predicted Curve") 725 | 726 | nextdays = [(datetime.strptime(d[-1],'%d %b')+timedelta(days=i)).strftime("%d %b") for i in range(1,prediction_days+1)] 727 | total =d+nextdays 728 | 729 | text = "Prediction for next "+str(prediction_days) +" days:\n" 730 | for i in range(prediction_days): 731 | text += nextdays[i]+" : "+str(np.round(data[-1*(prediction_days-i)],-1)[0]/thousand)+"K\n" 732 | 733 | plt.text(0.02, 0.78, text, fontsize=17, horizontalalignment='left', verticalalignment='top', transform=ax.transAxes,bbox=dict(facecolor='white', alpha=0.4)) 734 | 735 | # X-axis 736 | plt.xticks(list(np.arange(0,len(total),int(len(total)/5))),total[:-1:int(len(total)/5)]+[total[-1]]) 737 | 738 | # Tick-Parameters 739 | ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) 740 | ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) 741 | ax.tick_params(which='both', width=1,labelsize=12) 742 | ax.tick_params(which='major', length=6) 743 | ax.tick_params(which='minor', length=3, color='0.8') 744 | 745 | # Grid 746 | plt.grid(lw = 1, ls = '-', c = "0.7", which = 'major') 747 | plt.grid(lw = 1, ls = '-', c = "0.9", which = 'minor') 748 | 749 | # Plot Title 750 | plt.title("COVID-19 Next 10 day Prediction Curve-Global Deaths Cases",{'fontsize':22}) 751 | 752 | # Axis Lable 753 | plt.xlabel("Date",fontsize =18) 754 | plt.ylabel("Number of Deaths Cases (Thousand)",fontsize =18) 755 | 756 | # plt.yscale("log") 757 | plt.legend(fontsize =18) 758 | plt.tick_params(labelsize = 13) 759 | plt.savefig(out+"world_prediction_curve_deaths.png") 760 | #plt.show() 761 | 762 | 763 | 764 | # Data 765 | temp_data = np.nan_to_num(df_confirmed.sum()[5:].diff()) 766 | 767 | 768 | # Plot 769 | f = plt.figure(figsize=(15,10)) 770 | ax = f.add_subplot(111) 771 | 772 | 773 | date = np.arange(0,len(temp_data)) 774 | 775 | marker_style = dict(linewidth=2, linestyle='-', marker='o',markersize=5) 776 | plt.plot(date,temp_data/thousand,"-.",color="red",**marker_style) 777 | 778 | 779 | nextdays = [(datetime.strptime(d[-1],'%d %b')+timedelta(days=i)).strftime("%d %b") for i in range(1,prediction_days+1)] 780 | total =d+nextdays 781 | 782 | # X-axis 783 | plt.xticks(list(np.arange(0,len(total),int(len(total)/5))),total[:-1:int(len(total)/5)]+[total[-1]]) 784 | 785 | # Tick-Parameters 786 | ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) 787 | ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) 788 | ax.tick_params(which='both', width=1,labelsize=12) 789 | ax.tick_params(which='major', length=6) 790 | ax.tick_params(which='minor', length=3, color='0.8') 791 | 792 | # Grid 793 | plt.grid(lw = 1, ls = '-', c = "0.85", which = 'major') 794 | plt.grid(lw = 1, ls = '-', c = "0.95", which = 'minor') 795 | 796 | # Plot Title 797 | plt.title("COVID-19 Global Daily New Confirmed Cases",{'fontsize':22}) 798 | 799 | # Axis Lable 800 | plt.xlabel("Date",fontsize =18) 801 | plt.ylabel("Number of Daily Confirmed Cases (Thousand)",fontsize =18) 802 | 803 | # plt.yscale("log") 804 | plt.tick_params(labelsize = 13) 805 | plt.savefig(out+"daily_confirmed_cases_global.png") 806 | #plt.show() 807 | 808 | 809 | 810 | 811 | # Data 812 | temp_data = np.nan_to_num(df_deaths.sum()[5:].diff()) 813 | 814 | 815 | # Plot 816 | f = plt.figure(figsize=(15,10)) 817 | ax = f.add_subplot(111) 818 | 819 | 820 | date = np.arange(0,len(temp_data)) 821 | 822 | marker_style = dict(linewidth=2, linestyle='-', marker='o',markersize=5) 823 | plt.plot(date,temp_data/thousand,"-.",color="red",**marker_style) 824 | 825 | 826 | nextdays = [(datetime.strptime(d[-1],'%d %b')+timedelta(days=i)).strftime("%d %b") for i in range(1,prediction_days+1)] 827 | total =d+nextdays 828 | 829 | # X-axis 830 | plt.xticks(list(np.arange(0,len(total),int(len(total)/5))),total[:-1:int(len(total)/5)]+[total[-1]]) 831 | 832 | # Tick-Parameters 833 | ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) 834 | ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) 835 | ax.tick_params(which='both', width=1,labelsize=14) 836 | ax.tick_params(which='major', length=6) 837 | ax.tick_params(which='minor', length=3, color='0.8') 838 | 839 | # Grid 840 | plt.grid(lw = 1, ls = '-', c = "0.85", which = 'major') 841 | plt.grid(lw = 1, ls = '-', c = "0.95", which = 'minor') 842 | 843 | # Plot Title 844 | plt.title("COVID-19 Global Daily Deaths Reported",{'fontsize':22}) 845 | 846 | # Axis Lable 847 | plt.xlabel("Date",fontsize =18) 848 | plt.ylabel("Number of Daily Deaths Reported (Thousand)",fontsize =18) 849 | 850 | # plt.yscale("log") 851 | plt.savefig(out+"daily_deaths_cases_global.png") 852 | #plt.show() 853 | 854 | 855 | 856 | thoudand = 1000 857 | temp = df_confirmed.groupby('country').sum().diff(axis=1).sort_values(df_deaths.columns[-1],ascending =False).head(10).replace(np.nan,0) 858 | threshold = 0 859 | f = plt.figure(figsize=(20,12)) 860 | ax = f.add_subplot(111) 861 | for i,country in enumerate(temp.index): 862 | t = temp.loc[temp.index== country].values[0] 863 | t = t[t>=threshold] 864 | 865 | date = np.arange(0,len(t[:])) 866 | plt.plot(date,t/thoudand,'-o',label = country,linewidth =2, markevery=[-1]) 867 | 868 | 869 | nextdays = [(datetime.strptime(d[-1],'%d %b')+timedelta(days=i)).strftime("%d %b") for i in range(1,prediction_days+1)] 870 | total =d+nextdays 871 | 872 | # X-axis 873 | plt.xticks(list(np.arange(0,len(total),int(len(total)/5))),total[:-1:int(len(total)/5)]+[total[-1]]) 874 | 875 | # Tick-Parameters 876 | ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) 877 | ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) 878 | ax.tick_params(which='both', width=1,labelsize=14) 879 | ax.tick_params(which='major', length=6) 880 | ax.tick_params(which='minor', length=3, color='0.8') 881 | 882 | # Grid 883 | plt.grid(lw = 1, ls = '-', c = "0.85", which = 'major') 884 | plt.grid(lw = 1, ls = '-', c = "0.95", which = 'minor') 885 | 886 | # Plot Title 887 | plt.title("COVID-19 Daily Confirmed Cases in Different Countries",{'fontsize':24}) 888 | 889 | # Axis Lable 890 | plt.xlabel("Date",fontsize =18) 891 | plt.ylabel("Number of Daily Confirmed Cases (Thousand)",fontsize =18) 892 | 893 | # plt.yscale("log") 894 | plt.legend(fontsize=18) 895 | plt.savefig(out+"daily_confirmed_cases_countrywise.png") 896 | #plt.show() 897 | 898 | 899 | 900 | thoudand = 1000 901 | temp = df_deaths.groupby('country').sum().diff(axis=1).sort_values(df_deaths.columns[-1],ascending =False).head(10).replace(np.nan,0) 902 | threshold = 0 903 | f = plt.figure(figsize=(20,12)) 904 | ax = f.add_subplot(111) 905 | for i,country in enumerate(temp.index): 906 | t = temp.loc[temp.index== country].values[0] 907 | t = t[t>=threshold] 908 | 909 | date = np.arange(0,len(t[:])) 910 | plt.plot(date,t/thoudand,'-o',label = country,linewidth =2, markevery=[-1]) 911 | 912 | 913 | nextdays = [(datetime.strptime(d[-1],'%d %b')+timedelta(days=i)).strftime("%d %b") for i in range(1,prediction_days+1)] 914 | total =d+nextdays 915 | 916 | # X-axis 917 | plt.xticks(list(np.arange(0,len(total),int(len(total)/5))),total[:-1:int(len(total)/5)]+[total[-1]]) 918 | 919 | # Tick-Parameters 920 | ax.xaxis.set_minor_locator(ticker.AutoMinorLocator()) 921 | ax.yaxis.set_minor_locator(ticker.AutoMinorLocator()) 922 | ax.tick_params(which='both', width=1,labelsize=15) 923 | ax.tick_params(which='major', length=6) 924 | ax.tick_params(which='minor', length=3, color='0.8') 925 | 926 | # Grid 927 | plt.grid(lw = 1, ls = '-', c = "0.85", which = 'major') 928 | plt.grid(lw = 1, ls = '-', c = "0.95", which = 'minor') 929 | 930 | # Plot Title 931 | plt.title("COVID-19 Daily Deaths Reported in Different Countries",{'fontsize':24}) 932 | 933 | # Axis Lable 934 | plt.xlabel("Date",fontsize =18) 935 | plt.ylabel("Number of Daily Deaths Reported (Thousand)",fontsize =18) 936 | 937 | # plt.yscale("log") 938 | plt.legend(fontsize=18) 939 | plt.savefig(out+"daily_deaths_reported_countrywise.png") 940 | #plt.show() 941 | 942 | 943 | 944 | 945 | 946 | rows = 4 947 | f = plt.figure(figsize=(15,10*rows)) 948 | 949 | stats = [df_covid19.loc[:,['country','Confirmed']],df_covid19.loc[:,['country','Deaths']],df_covid19.loc[:,['country','Active']],df_covid19.loc[:,['country','Recovered']]] 950 | label = ["Confirmed","Deaths","Active","Recovered"] 951 | threshold = [50000,5000,20000,30000] 952 | for i, stat in enumerate(stats): 953 | plt.tight_layout() 954 | df_countries = stat.groupby(["country"]).sum() 955 | df_countries = df_countries.sort_values(df_countries.columns[-1],ascending= False) 956 | others = df_countries[df_countries[df_countries.columns[-1]] < threshold[i] ].sum()[-1] 957 | df_countries = df_countries[df_countries[df_countries.columns[-1]] > threshold[i]] 958 | df_countries = df_countries[df_countries.columns[-1]] 959 | df_countries["others"] = others 960 | labels = [df_countries.index[i] +" (" + str(int(df_countries[i])) +") "for i in range(df_countries.shape[0])] 961 | 962 | ax = f.add_subplot(rows,1,i+1) 963 | plt.pie(df_countries, labels=labels,autopct='%1.1f%%',pctdistance=0.85, labeldistance=1.2,textprops = {'fontsize':10.5}) 964 | my_circle=plt.Circle( (0,0), 0.7, color='white') 965 | p=plt.gcf() 966 | p.gca().add_artist(my_circle) 967 | plt.text(0.5,0.5,"World Total "+label[i]+ " COVID-19 Cases\n"+str(stat.sum().values[1]), horizontalalignment='center',verticalalignment='center',transform=ax.transAxes, size=18, alpha = 0.6) 968 | #plt.savefig(out+ str(label[i]) +"_countrywise_pie.png") 969 | 970 | plt.savefig(out+"all_countrywise_pie.png") 971 | #plt.show() 972 | 973 | 974 | 975 | df_data = df_table.groupby(['Last_Update', 'Country_Region'])['Confirmed', 'Deaths','continent'].max().reset_index().fillna(0) 976 | df_data["Last_Update"] = pd.to_datetime( df_data["Last_Update"]).dt.strftime('%m/%d/%Y') 977 | 978 | fig = px.scatter(df_data, y=100*df_data["Deaths"]/(df_data["Confirmed"]+1), 979 | x= df_data["Confirmed"]+1, 980 | range_y = [-1,18], 981 | range_x = [1,df_data["Confirmed"].max()+10000], 982 | color= "continent", hover_name="Country_Region", 983 | hover_data=["Confirmed","Deaths"], 984 | range_color= [0, max(np.power(df_data["Confirmed"],0.3))], 985 | animation_frame="Last_Update", 986 | animation_group="Country_Region", 987 | color_continuous_scale=px.colors.sequential.Plasma, 988 | title='COVID-19: Change in Mortality Rate of Each Countries Over Time', 989 | size = np.power(df_data["Confirmed"]+1,0.3)-0.5, 990 | size_max = 30, 991 | log_x=True, 992 | height =700, 993 | ) 994 | fig.update_coloraxes(colorscale="hot") 995 | fig.update(layout_coloraxis_showscale=False) 996 | fig.update_xaxes(title_text="Confirmed Cases (Log Scale)") 997 | fig.update_yaxes(title_text="Mortality Rate (%)") 998 | fig.write_html("mortalityrate_progression.html") 999 | #fig.show() 1000 | 1001 | --------------------------------------------------------------------------------