import csv
import matplotlib.pyplot as plt
import numpy as np


def transform(data):
    """Prepare the data for plotting

    Parameters
    ----------
    data : list
        A list of tuples. First element is the title of the question and the
        second one is a dictionary which maps the possible answer to the number
        of times the answer was given.
        [("Question1", {"yes":3, "no":4}, ("Question2", {"a":1, "no":2})]

    Returns
    -------
    tuple
        First element is a list of the titles of the questions. Second one is
        a dictionary mapping the possible answer to a list of the quantities
        the answer was given.
        (["Question1", "Question2"], {"yes":[3, 0], "no":[4, 2], "a":[0, 1]})
    """
    questions = [t for t, v in data]
    answers = list(set([k for t, v in data for k in v.keys()]))

    quantities = {}
    for answer in answers:
        quantities[answer] = [v[answer] if answer in v else 0 for t, v in data]

    return questions, quantities


def write_csv(data, fn):
    """Save data for plotting to a csv file

    Transform the data and save to csv file.

    Parameters
    ----------
    data : list
        A list of tuples. First element is the title of the question and the
        second one is a dictionary which maps the possible answer to the number
        of times the answer was given.
        [("Question1", {"yes":3, "no":4}, ("Question2", {"a":1, "no":2})]
    fn : str
        The name of the csv file.
    """

    questions, quantities = transform(data)

    if "" in quantities:
        quantities["no_answer"] = quantities[""]
        del quantities[""]

    with open(fn, "w") as csvfile:
        cw = csv.writer(csvfile)
        # header
        cw.writerow(["question"] + quantities.keys())

        for i, question in enumerate(questions):
            cw.writerow([question] + [v[i] for v in quantities.values()])


def create_barplot(data, fn=""):
    """Create a horizontal bar plot

    Parameters
    ----------
    data : list
        A list of tuples. First element is the title of the question and the
        second one is a dictionary which maps the possible answer to the number
        of times the answer was given.
        [("Question1", {"yes":3, "no":4}, ("Question2", {"a":1, "no":2})]
    fn : str, optional
        The name of the filename. If the filename is present, the plot will be
        saved to the file. Otherwise the plot will be displayed.
    """
    questions, quantities = transform(data)

    colors = [plt.cm.Set1(x) for x in np.linspace(0, 1, 9)]

    fig, ax = plt.subplots()
    y_pos = np.arange(len(questions))

    n = len(quantities.keys())
    width = 1./(n+1)

    for i, (k, v) in enumerate(quantities.items()):
        ax.barh(y_pos + i*width, v, width, color=colors[i],
                align="center", label=k if k else "keine Angabe")

    ax.set_yticks(y_pos + (n-1)*0.5*width)
    ax.set_yticklabels(questions)
    ax.set_ylim(-width, len(questions)-1+n*width)
    ax.invert_yaxis()
    ax.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=n,
              mode="expand", borderaxespad=0.)

    if fn:
        plt.savefig(fn)
    else:
        plt.show()

@@ -1352,33 +1352,102 @@
 nswer was given.
+ If there is no title for the answer, the%0A        key is set to %22na%22.
 %0A
-
         %5B(%22Quest
@@ -1655,16 +1655,9 @@
 s%5B%22n
-o_answer
+a
 %22%5D =
@@ -1889,16 +1889,16 @@
 tions):%0A
-
         
@@ -1965,16 +1965,1290 @@
 s()%5D)%0A%0A%0A
+def write_tex(data, fn):%0A    r%22%22%22Save data for plotting to a tex file%0A%0A    Create a tex file which contains the data as variables to build a plot.%0A    For the input%0A    %5B(%22Question1%22, %7B%22yes%22:3, %22no%22:4%7D, (%22Question2%22, %7B%22a b%22:1, %22c  d%22:2%7D)%5D%0A    the file contains%0A    %5Cnewcommand%7BQuestion1yes%7D%7B3%7D%0A    %5Cnewcommand%7BQuestion1no%7D%7B4%7D%0A    %5Cnewcommand%7BQuestion2ab%7D%7B1%7D%0A    %5Cnewcommand%7BQuestion2cd%7D%7B2%7D%0A%0A    Parameters%0A    ----------%0A    data : list%0A        A list of tuples. First element is the title of the question and the%0A        second one is a dictionary which maps the possible answer to the number%0A        of times the answer was given. If there is no title for the answer, the%0A        key is set to %22na%22.%0A        %5B(%22Question1%22, %7B%22yes%22:3, %22no%22:4%7D, (%22Question2%22, %7B%22a%22:1, %22no%22:2%7D)%5D%0A    fn : str%0A        The name of the tex file.%0A    %22%22%22%0A%0A    with open(fn, %22w%22) as f:%0A        for title, answers in data:%0A            for k, v in answers.items():%0A                if not k:%0A                    k = %22na%22%0A                f.write(%22%5C%5Cnewcommand%7B%7B%7B%7D%7B%7D%7D%7D%7B%7B%7B%7D%7D%7D%5Cn%22.format(%0A                                                        title.replace(%22 %22, %22%22),%0A                                                        k.replace(%22 %22, %22%22),%0A                                                        v))%0A%0A%0A
 def crea

Add tex export for statistics