在matplotlib中设置xticklabels,x轴格式

时间:2017-01-31 14:07:01

标签: matplotlib

我想在每个柱的中点用我们的x轴格式化图例值,同时保留性别组标识。为了清晰起见,我希望将性别群体降低到其他xtick标签下方。

到目前为止,我已经添加了xticks,但实际上正确地标记它们并且整齐地证明是比较棘手的。

enter image description here

from itertools import chain, cycle
import logging
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from pandas import DataFrame, Series
matplotlib.style.use("ggplot")


m = {"Males" :  {"Yes": 2, "No": 8}}
w = {"Females": {"Yes": 3, "No": 7}}
data = {**m, **w}
df = DataFrame(data)
# relative freq table
df_ft = (df / df.sum() * 100).T

ax = plt.subplot(111)
df_ft.plot(ax=ax, kind="bar", ylim=(0, 90),
           title="Would you prefer to work at home? (10 males, 10 females)",
           rot=0)
plt.ylabel("Relative Frequency (%)")


midp = 0.125  # standard bar width/2
t_l = ax.get_xticks().tolist()
ticks = list(chain.from_iterable((t - midp, t + midp) for t in t_l))
ax.set_xticks(t_l + ticks)

plt.show()

2 个答案:

答案 0 :(得分:1)

您可能正在寻找以下内容。

<?php
include("connection.php");
?>
<?php
$result=mysql_query("SELECT * FROM peralatansukan");

$count=mysql_num_rows($result);
echo"<select name=dropdown value=''>Dropdown</option>";
echo  "<table width='50%' border='1'>";
echo"<tr>";
echo"<td align='center'><b><font color='black'>No.</font></b></td>";
echo"<td align='center'><b><font color='black'>Peralatan Sukan</font></b>  
</td>";
echo"<td align='center'><b><font color='black'>Kuantiti</font></b></td>";
echo"</tr>";

if($count==0){
    echo "no record found";
}
else {
    while($row=mysql_fetch_array($result)){
        echo "<tr>";
        echo "<td align='center'><font color='black'>".$row["no"]."</font>  
        </td>";
        echo "<td align='center'><font  
        color='black'>".$row["peralatansukan"]."</font></td>";
        echo "<td align='center'>"."<option value=$row[kuantiti]></option>"." 
        </td>";
    }
    echo "</select>";
}

?>

enter image description here

答案 1 :(得分:-1)

Altair会在这里做得很好。

from altair import *
from pandas import DataFrame


df = DataFrame({'Males': {'Yes': 2, 'No': 8}, 'Females': {'Yes': 3, 'No': 7}})
df = df.stack().reset_index()
df.columns=['response','gender','count']

Vis#1

Chart(df).mark_bar().encode(x='gender',y='count',color='response').configure_cell(width=200, height=200)

enter image description here

Vis 2

Chart(df).mark_bar().encode(x=X('response', axis=False),
                            y=Y('count', axis=Axis(grid=False)),
                            color='response',
                            column=Column('gender', axis=Axis(axisWidth=1.0, offset=-8.0, orient='bottom'),scale=Scale(padding=30.0))).configure_cell(width=200, height=200).configure_facet_cell(strokeWidth=0)

enter image description here