wikimedica-disease-search/data/plot_pageviews.py

106 lines
3.0 KiB
Python
Executable File
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
import calendar
import collections
from datetime import datetime
from fetch import wikipedia_pageviews, mediawiki_api
import logging
import matplotlib
from matplotlib import pyplot
import sys
# Objet pour afficher le journal dexécution
logger = logging.getLogger('plot_pageviews')
logging.basicConfig(level=logging.INFO)
if len(sys.argv) < 4:
print("""Utilisation: {} [project] [output] [article]...
Représente sur un graphe les statistiques moyennes de vues de pages wiki.
Paramètres:
project Projet Wikipédia ciblé (par exemple fr.wikipedia.org).
output Nom du fichier de sortie où sera sauvé le graphe, ou '-' pour
afficher le résultat à lécran.
article Nom(s) darticle(s) Wikipédia ciblé(s).
Au moins un article doit être donné. Le nombre de visites est lissé avec un
noyau gaussien décart-type 10 jours. Les redirections darticle sont suivies
et toute visite sur une page de redirection pointant vers larticle est
dénombrée comme une visite sur la page canonique.
""".format(sys.argv[0]), end='', file=sys.stderr)
sys.exit(1)
project = sys.argv[1]
output = sys.argv[2]
articles = sys.argv[3:]
site = mediawiki_api.instanciate(project)
project_views = wikipedia_pageviews.get_aggregate(project)
output_to_file = output != '-'
if output_to_file:
matplotlib.use('pgf')
matplotlib.rcParams.update({
'pgf.texsystem': 'xelatex',
'font.family': 'serif',
'text.usetex': True,
'pgf.rcfonts': False,
})
fig = pyplot.figure(figsize=(4.7, 3.3))
ax = fig.add_subplot(111)
# Configuration de labscisse pour afficher les jours de lannée
ax.set_xlabel('Jours de lannée')
ax.set_xticks([
datetime(1, month, 1).toordinal()
for month in range(1, 13)
])
ax.set_xticklabels(calendar.month_abbr[1:13])
# Configuration de lordonnée pour être affichée en pourcentage
ax.set_ylabel('Proportion de vues par jour')
ax.yaxis.set_major_formatter(
matplotlib.ticker.FuncFormatter(
lambda y, _: '{:.5}'.format(y * 1000).replace('.', ',')
)
)
for article in articles:
canonical = mediawiki_api.article_canonical(site, article)
if article != canonical:
logger.info(
'Suivi de la redirection de « {} » en « {} »'
.format(article, canonical)
)
article = canonical
del canonical
redirects = mediawiki_api.article_redirects(site, article)
total_views = sum(
(wikipedia_pageviews.get_article(project, page)
for page in redirects + [article]),
start=collections.Counter()
)
relative_views = dict((
(date, total_view / project_views[date])
for date, total_view in total_views.items()
))
mean_views = wikipedia_pageviews.mean(relative_views)
smoothed_views = wikipedia_pageviews.smooth(mean_views, 10)
ax.plot(smoothed_views, label=article)
fig.legend(framealpha=1)
fig.autofmt_xdate()
fig.tight_layout()
if output_to_file:
pyplot.savefig(output)
else:
pyplot.show()